How to use get_template_part function
If you are looking for a tutorial that can teach you about get_template_part function. Then have came across the right place. Before jumping into the tutorial let’s take a quick look at what get_template_part function is ?
get_template_part function meaning
It is a WordPress function that is used to organize the WordPress files. A WordPress theme contains a lot of files. So it’s important to keep them in an organized manner. Basically we can say that get_template_part function is a mechanism provided by WordPress to keep reusable code separately.
As they are reusable pieces of code we can call them as many times as we wanted to.
How it works:
There are two parameters passed to use the get_template_part function.
get_template_part( 'template-parts/content', 'search' );
The first parameter is the slug of the of the template folder. It is basically the folder we want to include. The second parameter is the file that we want to use/include. In the example given above we have included the file content-search.php. We can simply divide this into three parts.
- ‘template-parts’ – It is the folder that contains template parts.
- ‘/content’ – It is the slug of the template.
- ‘search’ – It is the file that we want to include.
More Examples
There are many other ways in which the get_template_part function can be used. Here are some examples you might want to see.
get_template_part( 'content', get_post_format() );
This code will simply fetch the content-post-format.php.
get_template_part('content';
This code will fetch content.php file from the WordPress directory. Because we don’t have any folder to contain the file.
Conclusion
There are other ways to do the same thing as well. Means we have other methods that can pull data from a template. Still get_template_part function is the most recommended way.