How to add custom functions to a WordPress 1.5 theme?

By Angsuman Chakraborty, Gaea News Network
Tuesday, April 19, 2005

Recently the question (How to add add custom functions to a theme) was posed in WordPress Support Forum. Personally I faced the same question when re-designing this site. The following is a discussion of the option with the pros and cons.

There are two solutions.
The first is to create a plugin which goes with the theme. However the theme, when invoking functions defined in the plugin should check first for the availability of the function. It should also provide a fallback option if the plugin is not available or has not been activated.

if(function_exists('your_function_name')) {
    // Invoke your function: your_function_name()...
else {
    // Execute fallback option

The advantages are:

  • The plugin can be independently managed.
  • The plugin can be reused for other purposes.

The disadvantages are:

  • It requires another additional step for the theme user to remember.
  • It slightly complicates development and testing.

The second solution to this problem would be to incorporate the functionaility in a php file (as usual) which resides in the theme directory. This file is included in header.php like:
include (’your_php_file.php’);

Yes you may also require it for simplicity like:
require (’your_php_file.php’);

The advantage to this approach is simplicity of usage and deployment by end-users. It also simplifies development.

If the user later decides to switch to a different theme and yet wants to retain the functionality, he would have to re-purpose the custom code into a plugin.

In essence the reusability of the custom functionality determines the ideal location of the custom code.

June 4, 2005: 5:45 pm

Thanks for the advice. I’ll collect them all together if a my-hacks file until I;m complete then set about converting to a custom plugin as you suggest,Thanks again

June 3, 2005: 7:54 pm

As I mentioned above, I think you should just create a plugin and put them there.

Ideally in your template you can check if the function is available (or whether the plugin is active) and then use it, if not use the default WordPress function.

I too use several such customized functions on my site all packed away in a generic plugin named Impact (named after my custom theme).

June 3, 2005: 2:48 pm

Thanks for this. ~I am new to both WordPress and PHP but also wanted a few home cooked functions. In my case I wanted to change a couple of WP functions to return differently so I copied these, renamed them and made my changes so as not to disturb distributable files. Not knowing where to put them, I just created a my-hacks.php file and turned that one. All works fine. But is this NOT a good place to put my code?
Appreciate any advice. Thanks

will not be displayed