How to override a parent function from your Child Theme

When you’re writing a Child Theme you can easily add your own functions to a custom functions.php file. But sometimes you want to replace or remove a function that the original theme provides.

Because the Child Theme’s functions.php file is loaded BEFORE the parent’s file, you can’t just define the same function again because it would be overwritten. You also can’t rely on the original theme to provide a “pluggable” parent function, as suggested in the WordPress Codex.

What you can do however is to remove the parent’s function’s hook, and then re-hook your own function in its place. Let’s look at how to do this.

 

Removing the Parent Function

In this example the parent function has setup some styles which we don’t want, originally called via

add_action( ‘wp_enqueue_scripts’, ‘p2_iphone_style’, 1000 );

Let’s undo this:

// remove parent function
function my_theme_setup () {
	remove_action( 'wp_enqueue_scripts', 'p2_iphone_style', 1000 );
}
add_action( 'after_setup_theme', 'my_theme_setup' );

Note that you’ll have to provide all parameters from the original hook.

 

Replace the Parent Function with your own

If you want to do something else instead, define it with another function:

// replace parent function
function my_addition () {
	// your code goes here
}

function my_theme_setup () {
	remove_action( 'wp_enqueue_scripts', 'p2_iphone_style', 1000 );
	add_action( 'wp_enqueue_scripts', 'my_addition', 1000 );
}
add_action( 'after_setup_theme', 'my_theme_setup' );

First we remove the original action, then we add the same action again, plugging in our child theme’s function.

 

Further Reading





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.