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 as it will be overwritten. You also can’t rely on the original theme providing 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 both options now.

Removing the Parent Function

In this example the parent function has setup some styles which we don’t, 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: