WordPress Tip 101

Unhooking a Function from the Parent Theme

If the function from the parent theme isn’t pluggable, you can still prevent it from running. Imagine your parent theme has a function called parent_function(), which is hooked to the init hook with a priority of 20. You want to prevent it from running so you can replace it with a function of your own.

Here’s what the parent theme function might look like:

function parent_function() {
 //contents of function here
}
add_action( ‘init’, ‘parent_function’, 20 );

To unhook it, you’d code this in your child theme:

function remove_parent_function() {
 remove_action( ‘init’, ‘parent_function’, 20 );
}
add_action( ‘wp_head’, ‘remove_parent_function’ );

Note that you hook your second function to the wp_head hook which is run at the top of each page, and that you have to include the same value for the priority parameter as in the original function. If the original add_action() function didn’t have a priority, you can omit that from your child theme’s remove_action() function.

Note: If the original function was hooked to a filter hook instead of an action hook, you would use remove_filter() in the same way.

Augmenting a Function With Another Function

Instead of overriding or removing a function, sometimes you might want to add to it instead. In this case, you’d write a new function with a different name, and attach it to the same hook.

Let’s imagine there is an action hook for the footer in your parent theme called parent_footer. Any function you attach to that hook will run in the place where the hook is situated.

In the parent theme, there’s already a function called parent_footer_content() that populates the footer. But what if you wanted to add some extra code to it?

Here’s what the parent_footer_content() function might look like in the parent theme:

function parent_footer_content() {
 // content of function here
}
add_action( ‘parent_footer’, ‘parent_footer_content’ );

Now if you wanted to add additional content after that, you would create a function in your child theme, hooked to the same action hook, with a priority that meant it run after the first function. As the priority isn’t set for the parent theme’s function, it defaults to 10. So you need to use a higher number so it fires after that.

function child_footer_extra_content() {
 // contents of function here
}
add_action( ‘parent_footer’, ‘child_footer_extra_content’, 20 );

This would add the code from your child theme’s function after the code from your parent theme’s function.

An Example

This is a snippet I used to get rid of the footer in the Attitude theme


add_action( 'wp_head', 'remove_attitude_footer' );

function remove_attitude_footer() {
 remove_action( 'attitude_footer', 'attitude_footer_info', 30 );
}