The get_template_part()
template tag is simply a file-include call to include any arbitrarily named file. It is analogous to get_header()
to include header.php
, get_footer()
to include footer.php
, get_sidebar()
to include sidebar.php(), and
get_search_form()to include
searchform.php`.
Calling get_template_part( $slug )
will include a file named <strong>$slug.php
</strong>. The most common use case is get_template_part( 'loop' )
to include loop.php
, as a means of abstracting the loop code out of the main template files.
Calling get_template_part( $slug, $name )
will include a file named $slug-$name.php
. So continuing our example above, you could have a different loop output for different post formats (video, image, gallery, aside, etc.). Combining get_template_part()
with get_post_format()
yields a very powerful way to include post-format-specific loop output, via get_template_part( 'loop', get_post_format() )
. Using that call, if the current post has a post format of “gallery”, the loop-gallery.php
file would be included automatically.
But here’s the fun part: get_template_part()
is really just a fancy wrapper for locate_template()
: meaning that it is more powerful than a simple include()
call, because it has the built-in ability to fall back to less-specific files.
If you are using a Child Theme, and call get_template_part( $slug, $name )
, WordPress will attempt to include each of the following files, in order:
* $slug-$name.php
in the <em>Child</em> Theme
* $slug-$name.php
in the <em>Parent</em> Theme
* $slug.php
in the <em>Child</em> Theme
* $slug.php
in the <em>Parent</em> Theme
So if your parent Theme includes loop.php
, you can override that file just for posts that have the “gallery” post format, simply by including loop-gallery.php
in your Child Theme, and ensuring that you call get_template_part( 'loop', get_post_format() )
in the appropriate place(s).