get_template_part
Understanding get_template_part – Konstantin Kovshenin
Now comes the tricky part:
get_template_part( 'navigation', 'above' );
In a child theme context, this will look for the following templates in the following order:
- navigation-above.php in the child theme
- navigation-above.php in the parent theme
- navigation.php in the child theme
- navigation.php in the parent theme
The order is pretty important and something you should keep in mind.
Given this fallback model, it’s pretty common to use non hard-coded values with get_template_part
in themes. For example:
get_template_part( 'navigation', get_post_type() );
Where get_post_type()
will return the name of the post type that is currently shown, so if we’re on a Post, it’ll attempt to load navigation-post.php and fallback to navigation.php. If we’re on a Page, navigation-page.php and navigation.php. If we’re looking at a custom post type, say a Book, it will look for navigation-book.php and fall back to navigation.php.
A more common use case is post formats, with the post’s content area extracted into a template part of its own, like this:
get_template_part( 'content', get_post_format() );
Which will attempt to include content-gallery.php for gallery post formats, content-quote.php for quote post formats, and so on. If the particular file doesn’t exist, it will fall back to loading content.php. You can see this approach in action in the Twenty Eleven and Twenty Twelve themes.