Be nice to the children
When a new function arrives in WordPress and you want to make sure your theme still functions ok in older version of WP, you check to see if the function is supported first before defining it.
If for some unforeseen reason you needed to build and support a theme running on a version of WordPress older than 3.0—i.e., before the Nav Menu feature and the accompanying register_nav_menus()
function came along—prior to using the function, you’d need to wrap it in a if ( function_exists() )
conditional wrapper. e.g.
if ( function_exists( 'register_nav_menus' ) ) {
register_nav_menus(
array(
'main_menu' => __( 'Main Menu', 'butter' ),
'secondary_menu' => __( 'Secondary Menu', 'butter' ),
)
);
}
Having just covered Backward Compatibility, you know that unless you have to — both for your own sake and for the security of the WordPress installation — you really should upgrade to the latest version as opposed to supporting old versions.
Now, let’s say you’re building a parent theme that other developers or users can build child themes for. Most of the functionality of your theme will likely be defined in the functions.php
and specifically by functions.
Children come first!
The nature of child themes is such that functions declared within their functions.php
will take precedence over functions declared within the parent theme which they rely upon.
In the preceding example, we first checked to see if the register_nav_menus()
function was even possible to use in the currently installed WordPress version.
To allow for any child theme using your theme to re-define this same function, you must check to see that it DOES NOT already exist i.e., hasn’t already been defined by the child theme, before you declare it in the functions.php
.
The function would therefore look like this:
if ( ! function_exists( 'register_nav_menus' ) ) {
register_nav_menus(
array(
'main_menu' => __( 'Main Menu', 'butter' ),
'secondary_menu' => __( 'Secondary Menu', 'butter' ),
)
);
}
Notice the “ !
“. Now any child theme relying on this can overwrite this function as needed.
Naturally, you want to do this for more user-defined functions as opposed to core functions. e.g. if you define a function that outputs a list of your site’s contributors, its probably best to make that pluggable in case a different use-case for the function exists that’s better handled by overwriting the original function from within a child theme.