WordPress’s get_template_part() function: What and Why

get template part

This article introduces an important concept in WordPress themes: the WordPress get_template_part function. It’s one of the many important concepts of WordPress theme development. Mastering WordPress theme development is an important milestone in understanding WordPress development more generally. (We have a full free course on the topic, check it out.)

This content is not just one of our normal articles: it’s a sample chapter from our “learn WordPress development” guide Up and Running, our comprehensive summary of all the information a person needs to be rolling as a WordPress developer.

If you like this chapter, check out Up and Running. There’s about 40 more chapters where this one came from. It’s the best guide to WordPress development out there.

The Ultimate Way to Learn WordPress Development Concepts

Get Up and Running Today!

Up and Running is our complete “learn WordPress development” course. Now in its updated and expanded 3rd Edition, it’s helped hundreds of happy buyers learn WordPress development the fast, smart, and thorough way.

Key Takeaways about template parts in WordPress:

  • “Template parts” are incomplete pieces of WordPress PHP templates, pulled out into their own PHP files. Template files access them with a function called get_template_part().
  • The primary reason to create a template part in WordPress is to avoid repeating code: if multiple files use several identical lines of code, this code can be pulled into a template part, allowing it to be stored (and modified) in a single place.
  • get_template_part() can accept two arguments which, together, specify both a target template part file and a fallback file—much as the WordPress template hierarchy falls back to index.php. get_template_part() will also search the child theme (if one exists) for the targeted template part.

In WordPress, get_template_part() is a helpful way to avoid duplication and repetition within a WordPress theme. Use get_template_part() for any template code that you would otherwise end up copying-and-pasting. This chapter covers how WordPress’s get_template_part() function works, why get_template_part matters for WordPress themes, and how to use it in your own theme development.

What get_template_part() Is in WordPress

get_template_part() is a WordPress function that includes template “partials” wherever you need them. This allows you to centralize any block of code that is likely to be repeated into these “partials,” cutting down on duplication and making your template files more readable. Effective, it tells WordPress to load template parts, like the body of a post in different theme files (which are usually part of the template hierarchy).

Let’s take an example Loop in an index.php file, using get_template_part():

/* Environment: We're in index.php */

if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        get_template_part( 'content' );
    endwhile;
endif;

And here’s our example content.php:

/* Environment: We're in content.php */

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <h2 class="entry-title">
	    <a href="<?php the_permalink(); ?>">
	    	<?php the_title(); ?>
	    </a>
	</h2>

    <?php the_excerpt(); ?>
</article>

In this example, WordPress will load up index.php, and it will run as if the contents of content.php were inside it. You can think of it as being WordPress loading in the “sub-template” completely in the line where get_template_part() was called. This lets us avoid rewriting (or maintaining) all the same code around the various files of our WordPress theme.

Breaking this one file into two has a number of advantages:

  1. Both index.php and content.php are now compact and readable.
  2. The two files now have distinct responsibilities: index.php contains mostly logic, and content.php contains mostly presentational HTML/PHP templating code.
  3. The major advantage: the code in content.php can be reused by other template files, like home.php, simply by having those files also call get_template_part( 'content' ). This cuts down on the overall bulkiness of the theme, and it prevents repetition: if you want to change something about content.php, you only change it once, and the changes propagate everywhere.

WordPress Get Template Part Filenames are Arbitrary, Can Be Variables

One thing to note from this example: content.php is an arbitrary name—you can name your template parts anything you want. get_template_part( 'anything' ); would work perfectly fine, as long as the theme (or its child or parent theme) contains a file called anything.php. That name, specifically, we don’t recommend. But it’s important to know as different themes you’ll see do it differently.

Using get_template_part() with a Second Parameter

You can use a second parameter on get_template_part(), which makes it even more powerful.

This second parameter is probably easiest to explain by example. We’ll assume that we’re using a child theme. The code, with a second parameter, is as follows:

<?php get_template_part( 'first', 'second' ); ?>

Based on this code, WordPress will look for the following files, in order:

  1. In the child theme: first-second.php
  2. In the parent theme: first-second.php
  3. In the child theme: first.php
  4. In the parent theme: first.php

Filenames and get_template_part() with Two Arguments

To make the pattern above explicit:

<?php get_template_part( 'firstargument', 'secondargument' ); ?>

Will look for a file named firstargument-secondargument.php—both arguments, combined and separated by a hyphen. If this file isn’t found, WordPress will fall back to simply firstargument.php. In both cases, it will look for these files first in the child theme (if one exists), then in the parent theme.

The Usefulness of get_template_part() with Two Arguments

As a real-world example: you may want to specify a content-page.php template part that works specifically for Pages; if this file is missing, WordPress simply falls back to content.php. This is very similar to how all templates fall back to index.php in the template hierarchy, eliminating the risk that WordPress will be unable to process a certain kind of content.

This method also tends to lead to helpful, descriptive template part names, as in Twenty Fifteen:

Configure a CDN for your offloaded media

With get_template_part, passing variables to the second argument is also rather common. Passing variables to get_template_part is useful because it allow us to have things (like the WordPress post format) stored as a variable and then passed in to the function. Or we can simply have what could have been a variable declarion stand as a function-call inline, like this line from the Twenty Nineteen theme:

get_template_part( 'template-parts/post/content', get_post_format() );

WordPress Child Themes: Why get_template_part() is Better than PHP’s include() or require()

If you know PHP well, you might wonder: “Why not just use PHP’s include() or require() functions to pull in the template part files?” These functions will indeed work as designed; however, they’re not the “WordPress way” of doing it, and that has specific downsides.

First, the default PHP functions do not have the “two arguments with fallbacks” structure of get_template_part(), as covered above. This means that a file moving, or not having an expect fall back will just break. That’s bad.

The second, and more important reason is child themes. For a child theme to modify a template part file—for example, a child theme that creates its own version of content.phprequire simply won’t work. It’s not “child theme aware” which is a really important thing for WordPress themes.

With get_template_part(), the child’s content.php can simply replace the parent’s—but since include() and require() pull in files in a “non-WordPress” way, the child theme must instead replace every theme file that uses these template parts, creating huge unnecessary bulk in the child theme.

So when your “parent theme” has used get_template_part take advantage. Just write the template part you need to override, and nothing more. The feature of get_template_part will help you. And, if you write your own theme, you should always use get_template_part() where possible. It’ll make everyone happier.

That’s All About WordPress Template Parts!

WordPress’s get_template_part() is a powerful and valuable part of WordPress theming. You’ll see it in most good themes you try to edit, so we hope you now know what it’s doing and why it’s valuable.

Up and running wp

Summary Limerick

A template is whole when it starts,
But it’s often best broken in parts.
This cuts repetition
And helps with concision,
And shows off your WordPressing smarts.

Quiz Time! 💡

Do You Understand get_template_part?

  1. A template part is:
    1. A complete, but succinct, page template
    2. The section of a WordPress template that’s inside The Loop
    3. A section of a template file—generally likely to be repeated across multiple template files—broken out into its own PHP file
  2. Template parts are a good idea for all of these reasons except:
    1. They reduce repetition and code bulk inside a theme
    2. They make it easier to track down and debug PHP errors
    3. They allow a “search-and-fallback” template system, much like the WordPress template hierarchy
  3. get_template_part( 'content', 'page' ); will search for:
    1. content-page.php, falling back to page.php
    2. content-page.php, falling back to content.php
    3. content.php, falling back to page.php

Answers and Explanations 🏆

1. Answer:

C. defeats the purpose of template parts. B could be true, but a template part can be made from any amount of code, either inside or outside of The Loop.

2. Answer:

B. is the primary argument in favor of template parts, and C is a secondary benefit.

3. Answer:

B. WordPress will search for content-page.php, first in the child theme (if one exists) and then the parent theme, and then fall back to content.php, first in the child theme and then the parent theme. Remember that the two function arguments are combined, and separated by a hyphen, to make the template part’s filename.


3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
gk
July 17, 2019 2:04 am

What about CSS ??????? How would you recommend organizing the CSS of each part file?

Povilas
September 16, 2019 1:37 am
Reply to  gk

With CSS you can use SASS (SCSS) which you can then compile to CSS. It is a very useful tool for organizing styling code and has all kinds of features to make your code used for styling less repetitive and easier to manage. Even if you look at twentynineteen theme (the newest one for now) SCSS is being used for that purpose.

Mike S.
March 25, 2019 1:22 pm

Thanks guys, good info! But I started getting lost at the second parameter section.

I also didn’t track the child theme/include/require section at all. I think an example use case of doing it one way versus the other way would help me… maybe?

Thanks for your time. By the way I’ve been considering buying Up & Running but my biggest hesitation is the fact I run into stuff I don’t understand in many of the posts you share from the curriculum. It’s not really 101-level to me. Do you have a “for dummies” version?