WordPress allows theme developers to manage their theme template files in many different ways. But certainly,
get_template_part is the best version of it.
It uses core WordPress functions to find and load a specific PHP file. Basically, it is like PHP include, but on steroids.
In this post, we will show you a few use cases and sample codes for WordPress
get_template_part – How Does it Work?
get_template_part has two string inputs. The first input is the slug of the template we want to include. If you would like to include
share.php in your theme after the post, then you can simply use
'share' as the first parameter, as in the following sample code:
<?php get_template_part( 'share' ); ?>
Please note that we are not using a PHP extension here. WordPress uses require function for including PHP files. So, you can call
get_template_part multiple times on your page.
get_template_part vs include/require
When you use get_template_part instead of include or require statements, you are making sure that the theme won’t give any errors when that template is missing.
Theme developers can use this statement to extend their themes using child themes. get_template_part first checks the child theme for the included file. If that file doesn’t exist, then it gets that template part from the parent theme.
get_template_part – Subfolders Example
Another handy example can be using it for ad code insertion. I generally keep ad codes in separate PHP files. If you want to load a specific ad code to your theme sidebar, you can use the following code to handle this:
<?php get_template_part( 'partials/ads', 'top-banner' ); ?>
As you can see, you can include templates from subfolders without any issues.
First, this function looks for an exact match combining two parameters: ‘partials/ads-top-banner.php’. If it can not find top-banner as a PHP file, then it will fall back for ‘partials/ads.php’. If that file doesn’t exist either, it will simply discard this function call, and it won’t cause any issues.
Some developers like using hooks and actions while developing WordPress themes. But, I generally prefer
get_template_part to make my theme more manageable. Using
get_template_part gives you a better understanding of what is going to be displayed there. And if you want to edit just this portion of the site, you edit that template file and it will be done.
What is your use case for
get_template_part? Share it with us in the comments!