Template Parts

Learn to reduce code duplication through template parts.

Template parts

A template part is a theme file that contains code used by multiple theme files. It is used to reduce code duplication. Just like the get_header() and get_footer() functions which include the header and footer, the get_template_part() function is used to include a custom theme file.

Let’s consider a use case. The code that displays the event with its date and a brief summary is duplicated at three different places:

  1. On the homepage

  2. On the events archive page

  3. On the past events archive page

We can remove this duplication by moving this code into its own file and calling the file in place of the code.

The code to display an event is followed by a default or custom query. The query decides which posts to display based on the requirements of the page, for example filter out future events or past events. However, the HTML code to display the event inside the while loop is always the same as shown below:

Get hands-on with 1400+ tech skills courses.