Wordpres Get Template Part Wpassist

WordPress allows theme developers to manage their templates 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. So, 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 function.

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 use the following sample code:

<?php get_template_part( 'share' ); ?>

Please note that we are not using 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 – Sub Folders Example

Another handy example can be AdSense ad codes. I generally keep ad codes under 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.

Conclusion

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!

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *