Adding Action Hooks In Parent Theme For Easier Child Theme Customization

I was wondering why isn't anyone (haven't be able to find one with it) adding custom hooks an the beginning and at the end of the theme's function.php for theme development.

The reason I'm asking this is while making a child theme, I had to overwrite some default setups like image sizes set in the parent theme's main function.php (no !function_exists to overwrite on). So anything I write in my child's function.phpwill be overwritten.

Aside from of course adding the function_exists wrapper, the solution I had in mind was just adding a do_action() at the beginning and at the end of the function.php. But is this a bad practice? If so, why?

I am unable to find any answers or anyone asking this anywhere.

Answers 1

  • Code in a functions.php (or any file loaded by that file) should not run automatically, eg. when the file is included. All code should be bound to hooks.
    That means, you don’t need a special action in the parent theme. The child theme can turn off all parent theme callbacks with remove_action() and remove_filter().

    But you can make that easier for child theme authors by adding a custom action after you have registered the callbacks.


    Parent theme

    namespace ParentTheme;
    // register callbacks
    add_action( 'after_setup_theme', __NAMESPACE__ . '\setup_custom_background' );
    add_action( 'after_setup_theme', __NAMESPACE__ . '\setup_custom_header' );
    add_filter( 'body_class',        __NAMESPACE__ . '\enhance_body_class' );
    // provide an entry point
    do_action( 'parent_theme_loaded', __NAMESPACE__ );

    Child theme

    add_action( 'parent_theme_loaded', function( $namespace )
        remove_action( 'after_setup_theme', $namespace . '\setup_custom_header' );

    See also this similar example for outdated PHP versions.

    If your parent theme ignores the principle of separation of concerns and mixes everything in just one or two setup functions, use a later priority and overwrite those calls:

    Parent theme

    add_action( 'after_setup_theme', 'some_setup_function' ); // priority = 10

    Child theme

    add_action( 'after_setup_theme', 'fix_theme_setup', 11 ); // priority = 11
    function fix_theme_setup()
        remove_theme_support( 'post-formats' );
        // more changes here

Related Questions