When you are developing custom WordPress themes you may need to organize your code into different folders and files, or template parts.
Apart from that, if you plan on using the same theme on multiple sites or even selling it, you may want to allow other people to override different parts of your theme in their child theme.
That’s where WordPress’s get_template_part function becomes handy.
The get_template_part Function Definition
If you take a look at the developer documentation, the function is defined in the following way:
<?php
function get_template_part(string $slug, string $name = null, array $args = array());
The function can accept 3 parameters:
- $slug – the slug of the generic template you want to include
- $name – the name of the specialized template
- $args – additional arguments you want to pass to the template
How To Use get_template_part Function?
In order to better understand how this function works, let’s take a look at the following example. Imagine you have 2 partials for pagination with different styles that you want to include in multiple places.
The partials are located inside your theme in the partials/pagination-style1.php and partials/pagination-style2.php.
In order to include the pagination with the 1 style, you can use the following code:
<?php
get_template_part('partials/pagination', 'style1');
Let’s take a look at another example. Let’s assume we have a partial to display a blog post in a card format which is located in the partials/content-card.php.
However, this time we also want to pass the post title, excerpt, and link to our partial because it needs to display that data.
Here is how we can do it:
<?php
foreach($posts as $post) {
get_template_part('partials/content', 'cart', [
'title' => $post->post_title,
'excerpt' => get_the_excerpt($post->ID),
'link' => get_permalink($post->ID)
]);
}
?>
get_template_part Function Hooks
Just like almost any other WordPress’s core function, the get_template_part function users 2 actions internally that give you some level of flexibility.
The first one is:
<?php
// $slug is the name of the slug you've passed to your function
do_action("get_template_part_{$slug}", $slug, $name, $args);
And the second one, which is more generic:
<?php
// $slug is the name of the slug you've passed to your function
do_action('get_template_part', $slug, $name, $templates, $args);
Wrapping Up
As you can see, WordPress’s get_template_part function gives you a lot of flexibility when you want to develop or customize your theme. It’s also a great way to allow other developers to override certain parts of your theme in their child theme.