7

I want to redeclare a function that I inherited from the parent theme.

When I do it in functions.php, I get a fatal error that redeclaration is not possible.

I did a workaround: creating a modified function name and copying all the template files, index.php etc. into the child theme's directory and rewriting the function calls. So now the new function is called.

This works but ignores any updates that the parent theme would have.

Is there a better solution to this?

2 Answers 2

9

Redeclaring a function in a child theme only works when the parent themes' function is wrapped in a

 if( !function_exists( 'function_name' )):

condition. Then you can simply just copy the complete function to the child theme and do whatever modifications you need to do.

If the parent themes' functions aren't wrapped in that if conditional statement, and if no filters or hooks are supplied in the function, it will be best to copy the function to your child theme, rename that function, do your modifications and then update your template files accordingly to reflect the new function.

3
  • 2
    That is exactly what I did. Now I see that this is a fault of php as it does not enable redeclaration as javascript does.
    – Gergely
    May 24, 2014 at 9:22
  • Info on WordPress hooks/filters: codex.wordpress.org/Plugin_API Sep 25, 2017 at 21:34
  • 1
    But won't the function be overridden by a theme update ? Maybe I do not understand the steps you said - I will reiterate: I copy the function I want to update and I rename the original function. Then, when I update my theme, the original function will be renamed again to its original name. Am I missing something?
    – Victor
    Aug 27, 2020 at 9:05
3

You can first remove the function with

remove_filter( 'hook', 'function_name' );

and then add the function again with the new name and same hook.

For Example

    function remove_content_filter() {

       remove_filter( 'the_content', 'function_name' );

    }

    add_action( 'after_setup_theme', 'remove_content_filter' );

    function new_function_name( $output ) {
        //some code here
        return $output;
    }

    add_filter( 'the_content', 'new_function_name' );
1
  • 1
    I believe you can do this only if the function was added to the filter in the first place. Otherwise, if it is a normal function (not pluggable or any other king), then you can not do this. Am I right ?
    – Victor
    Aug 27, 2020 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.