Is it possible to override the result of get_template_part()?

I’m working on a child theme, I strongly prefer not to override the main template files in order to maintain simplicity of the child theme as well as minimize the amount of code and maintenance over time.

In the loop, the index.php template in parent theme uses:
get_template_part( 'content' );

which will bring in content.php, I’m looking to have it behave more like get_template_part( 'content', get_post_format() ); or similar in order to bring in different templates such as content-aside.php, etc, without creating an index.php in the child theme to overwrite the parent for a single line change.

get_template_part() consists of:

function get_template_part( $slug, $name = null ) {

    do_action( "get_template_part_{$slug}", $slug, $name );
    $templates = array();
    $name = (string) $name;
    if ( '' !== $name )
        $templates[] = "{$slug}-{$name}.php";

    $templates[] = "{$slug}.php";
    locate_template($templates, true, false);
}

So there’s an action available, in my case called get_template_part_content

I can hook onto the action with something like:

add_action( 'get_template_part_content', 'child_post_styles', 10, 2 );

function child_post_styles ( $slug, $name ) {
    if( false == $name ){
        $name = get_post_format();
        $templates = array();
        if ( '' !== $name )
            $templates[] = "{$slug}-{$name}.php";

        $templates[] = "{$slug}.php";
        locate_template($templates, true, false);
    }
}

This obviously results in post duplication, one from my hooked function, which can display the desired template, and the other from the normal locate_template call in get_template_part()

I’m having trouble finding a way to accomplish this without duplication, or without ending page render right after serving my template part by doing something stupid such as a break or exit

4 s
4

There is no hook to do this. Copy the index.php to the child theme and make the single line change. Also, tell the parent theme’s author that they should make the same change in their theme, for flexibility.

Leave a Comment