A Note About get_template_part and Child Themes

Tip: if you’re wondering why your WordPress template file (for example index.php) is not being executed, perhaps a different file (archive.php) is overriding it. Now this may sound obvious, but not when you start using get_template_part to organize your theme files, and not when you’re making a child theme.

Let’s take a quick look at the following snippet:

get_template_part( 'content', get_post_format() );

That will look for files like content-link.php, content-gallery.php and so on, and will always fall back to content.php if none of the others are found. Now, imagine you’re working on a child theme. You create content.php and content-gallery.php. You expect gallery posts to pick up content-gallery.php, which is correct.

You also expect a link post to pick up your content.php file because there is no content-link.php in your child theme, right? This is also correct, unless your parent theme has a content-link.php file, which will be of higher priority to the template loader, despite the child-parent relationship between the two themes.

It does make sense, otherwise a simple index.php file in your child theme would override all of the parent theme’s templates, because index.php is a fallback for everything. That would render child themes useless.

So when working with get_template_part (and theme templates in general, thanks Chip!) especially child themes, don’t forget to check (and preferably study) the parent theme’s template files. Also keep the template hierarchy fresh in your head every time you create a new theme template file. It tends to evolve with every release.

2 thoughts on “A Note About get_template_part and Child Themes

  1. Good stuff, Konstantin!

    The important thing to remember with get_template_part( $file, $slug ) is that it is essentially a fancy wrapper for locate_template(), in which the array of templates to search is built such that it searches in the following order:

    – $file-$slug.php in child
    – $file-$slug.php in parent
    – $file.php in child
    – $file.php in parent

    So, it’s not really so much a matter of the template hierarchy. In fact, get_template_part() and locate_template() are entirely independent from the template hierarchy/template loader. Both functions return FALSE rather than fallback to index.php if the specified template file isn’t found.

    • Hey Chip, thanks for your comment! The return value being false for the functions, rather than falling back to index.php, is valuable info, and good to know! Of course, otherwise we couldn’t risk using the functions for stuff other than the main template files, which would be even more useless outside the core.

      Thanks again for stopping by! :)

Comments are closed.