Part of the process of developing a website is recognizing when certain design patterns appear in multiple places and pages. The header and footer are examples of code that is written once and then called through a function to appear on multiple pages. WordPress has these functions available for us to place on the page. But what if we have code that appears throughout multiple pages on different page templates?
This is where get_template_part() becomes useful. It is a way for developers to organize and reuse code in a WordPress theme. Template parts are incomplete pieces of WordPress PHP templates that get pulled out into their own PHP file.
Creating a template part is easy, you first start out by creating a new PHP file. For example, we can create a file called template-example.php. It’s best to create a separate folder for template parts in the site’s theme to keep everything organized. In this newly created template-example.php, you can type the code that you want to reuse.
In order to implement this code in the page template that you want, you can then paste this code in the section where you want the code to display.
In the page template:
<?php get_template_part("template-parts/template-example.php"); ?>
Keep in mind if you are placing your files in its own designated folder make sure to include it when you call it.
Examples of using a template part in WordPress
Template parts are effective for reusing code. If you have a section that pulls images from Instagram or tweets from twitter and want to have that displayed on different sections of the website, get_template_part() is useful for that.
This function also works well with WordPress plugins like Advanced Custom Fields, a plugin that allows developers to create fields for WordPress’s admin pages. Using both of these combined, you can create sliders and image carousels that can be used on multiple templates using different content entered in the fields. So you can create a template part called “image-carousel.php”, create the fields in the backend and use them for the pages that you want the carousel to appear. A carousel on one page can use a different set of images on another page without having to change the code.