Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 68 ยท Classic Themes and the Template Hierarchy

Template Parts and Template Tags

Split a classic WordPress theme into reusable template parts with get_template_part, pass data with args, and write your own safe template tags.

A theme with one giant single.php and a copy of the same card markup in archive.php, search.php and index.php is a theme that is hard to change. WordPress gives you two tools to avoid that. Template parts are small PHP files that you include from other templates. Template tags are functions that print or return one piece of data, such as a title, a permalink or a URL.

In this lesson you will learn how get_template_part() finds files (and why it tries a specific file before a generic one), how to pass data into a part, the difference between the_* and get_the_* functions, and how to write your own template tags that are safe to use. The first example in this lesson is a runnable stand-in for the lookup logic. Real WordPress cannot run on this site, so all WordPress code in code blocks is read-only, and the runnable examples are plain PHP that mimics the behavior. The lesson says clearly which is which.

You should know the loop from The Loop and the theme basics from Your First Classic Theme.

get_template_part: include a file by slug and name

get_template_part() loads another PHP file from the theme. Its signature has three parameters:

PHP
get_template_part( string $slug, ?string $name = null, array $args = [] ): void|false

The $slug is the path without .php, relative to the theme folder. The optional $name makes the request more specific. WordPress builds a list of candidate file names and loads the first one that exists:

  1. -{name}.php (only if you gave a name)
  2. .php

The lookup happens in the child theme first and then in the parent theme (see Child Themes). That is why the call below is a very common pattern inside a loop:

PHP
while ( have_posts() ) {
    the_post();
    get_template_part( 'template-parts/content', get_post_type() );
}

For a post of type post WordPress looks for template-parts/content-post.php. For a page it looks for template-parts/content-page.php. For a custom type called book it looks for content-book.php. Whenever the specific file is missing, the generic template-parts/content.php is the fallback. You get a sensible default for everything and can specialise only the types that need it.

If neither file exists, get_template_part() does nothing and returns false. It does not throw an error. A typo in a slug therefore shows up as a missing section on the page rather than as a warning, so check your file names when a part does not appear.

Under the hood, get_template_part() calls locate_template(), which does the actual searching, and it also fires an action named get_template_part_{$slug} before loading. You will rarely need that hook, but it explains how plugins can react when a part loads.

The lookup, step by step

PHP get_template_part stand-in: specialised first, generic second

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The post type has no specific file, so the generic content.php is used. page and book each get their own file. The final call finds nothing and prints nothing, exactly like the real function.

flowchart TD
    A["get_template_part('template-parts/content', 'book')"] --> B{"content-book.php<br/>in child theme?"}
    B -- yes --> Z["Load it"]
    B -- no --> C{"content-book.php<br/>in parent theme?"}
    C -- yes --> Z
    C -- no --> D{"content.php<br/>in child theme?"}
    D -- yes --> Z
    D -- no --> E{"content.php<br/>in parent theme?"}
    E -- yes --> Z
    E -- no --> F["Return false, print nothing"]

The specific name is tried in both themes before the generic name is tried at all.

Passing data with $args

Since WordPress 5.5, the third parameter lets you hand data to the part. Inside the part file, the array is available as a variable called $args:

PHP
// In archive.php
get_template_part(
    'template-parts/card',
    null,
    [
        'show_excerpt' => true,
        'heading_tag'  => 'h3',
    ]
);
PHP
<?php
// template-parts/card.php
$args = wp_parse_args( $args, [
    'show_excerpt' => false,
    'heading_tag'  => 'h2',
] );
?>
<article <?php post_class(); ?>>
    <<?php echo tag_escape( $args['heading_tag'] ); ?>>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </<?php echo tag_escape( $args['heading_tag'] ); ?>>
    <?php if ( $args['show_excerpt'] ) { the_excerpt(); } ?>
</article>

Two habits make this reliable. First, always merge $args with defaults using wp_parse_args(), because the same part may be called without any arguments from another template. Second, treat the values as untrusted when you print them: tag_escape() here keeps a heading tag name safe.

A part still runs inside the same scope as the loop, so the global post is available. You can pass an ID in $args when you want a part to render a specific post outside the main loop, but passing data explicitly makes the part easier to test and reuse.

Finding files with locate_template

locate_template() is the lower-level function that get_template_part() uses. Give it an array of file names in priority order. It returns the full path of the first match, searching the child theme and then the parent:

PHP
$path = locate_template( [ 'template-parts/hero-home.php', 'template-parts/hero.php' ] );

if ( $path ) {
    load_template( $path, false, [ 'title' => 'Welcome' ] );
}

Passing true as the second argument loads the file immediately, and a third argument of true means require_once. Use locate_template() directly when you need a custom fallback chain that does not fit the slug-and-name pattern, for example when a plugin wants to let a theme override its markup.

Template tags: the_* versus get_the_*

A template tag is a PHP function intended for use in theme files. Most core tags come in two flavors, and the naming convention is consistent:

Function What it does Typical use
the_title() Prints the title Directly in markup
get_the_title() Returns the title as a string When you need to change or reuse it
the_permalink() Prints the URL href="<?php the_permalink(); ?>"
get_permalink() Returns the URL Building links or JSON
the_excerpt() Prints the excerpt Archive cards
get_the_excerpt() Returns the excerpt Meta descriptions, truncation

The rule: the_ echoes, get_ returns. There are exceptions to the naming (get_permalink() has no get_the_ form, and the_post_thumbnail() prints while get_the_post_thumbnail() returns), but the pattern holds for nearly every tag. When you write echo get_the_title() you own the output, so remember that returned values are not automatically safe for every context. Titles and excerpts can contain HTML entities, so escape them for the place you print them: esc_html( get_the_title() ) inside text, esc_attr() inside an attribute. Escaping is covered in depth in Escaping Output.

Site and URL tags

A handful of tags give you site-wide information and URLs:

PHP
bloginfo( 'name' );                     // prints the site title
echo esc_html( get_bloginfo( 'name' ) ); // returns it, so you escape and print
echo esc_url( home_url( '/' ) );        // https://example.com/
echo esc_url( get_template_directory_uri() . '/assets/logo.svg' );
echo esc_url( get_stylesheet_directory_uri() . '/assets/logo.svg' );

home_url() builds URLs from the site address and accepts a path. The two directory functions differ only when a child theme is active: get_template_directory_uri() always points to the parent theme, while get_stylesheet_directory_uri() points to the active (child) theme. If your asset ships in the child theme, use the stylesheet one. The matching filesystem helpers are get_template_directory() and get_stylesheet_directory().

Writing your own template tags

When a snippet of logic appears in more than one template, wrap it in a function in functions.php or a file such as inc/template-tags.php that functions.php loads. Follow the same convention as core: one function that returns, and one that prints by calling the first. Prefix everything with your theme's slug so names never collide with a plugin.

PHP
function mytheme_get_reading_time( ?int $post_id = null ): int {
    $content = get_post_field( 'post_content', $post_id ?? get_the_ID() );
    $words   = str_word_count( wp_strip_all_tags( $content ) );
    return max( 1, (int) ceil( $words / 220 ) );
}

function mytheme_the_reading_time(): void {
    printf(
        '<span class="reading-time">%s</span>',
        esc_html( sprintf( _n( '%d minute read', '%d minutes read', mytheme_get_reading_time(), 'mytheme' ), mytheme_get_reading_time() ) )
    );
}

Calling mytheme_the_reading_time() in any template prints the line, and mytheme_get_reading_time() stays usable for other code. All escaping happens at the point of output, which is the safe habit.

PHP A pair of template tags: one returns, one prints

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The runnable version uses htmlspecialchars() in place of esc_html() and a plain array in place of the global post. The real functions call WordPress internals, but the shape is the same: a returning function, a printing function that wraps it, and escaping when the value reaches HTML.

Common mistakes

  • Putting logic in the template. A part should mostly print. Move queries and calculations into functions so they can be tested and reused.
  • Forgetting the generic fallback. If you only create content-book.php, other types print nothing. Always ship content.php.
  • Hardcoding URLs. Use home_url() and the directory URI functions so the site works on any domain, in a subfolder, or behind a child theme.
  • Echoing get_ values without escaping. get_ functions hand you the data, so you are responsible for output safety.
  • Unprefixed function names. Use mytheme_ (or a namespace) so a plugin cannot collide with you.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. For a custom post type book, which file does get_template_part( 'template-parts/content', 'book' ) try first?

    WordPress joins the slug and the name with a hyphen, tries that file first, and only then falls back to the slug alone.
  2. 2. What happens when neither the specific nor the generic part file exists?

    get_template_part() fails quietly. It returns false and outputs nothing, so a typo in a file name can hide a missing section.
  3. 3. Inside a template part, how do you read the data passed as the third argument of get_template_part()?

    Since WordPress 5.5 the array you pass is available in the part as $args. Merge it with defaults using wp_parse_args().
  4. 4. A child theme is active and ships its own logo. Which function builds the correct URL?

    get_template_directory_uri() always points to the parent theme. get_stylesheet_directory_uri() points to the active theme, which is the child.
  5. 5. What is the naming convention for template tags that print versus return?

    The convention is the_something() echoes and get_something() returns the value. A few core functions break the naming, but most follow it.

Summary

  • get_template_part( $slug, $name, $args ) loads -{name}.php, then .php, checking the child theme before the parent, and does nothing if neither exists.
  • Pass data with the third argument; read it as $args and merge it with defaults using wp_parse_args().
  • locate_template() finds a file from your own list of candidates and is what get_template_part() uses internally.
  • the_* tags print and get_* tags return; escape returned values for the context where you print them.
  • Use home_url(), get_template_directory_uri() and get_stylesheet_directory_uri() instead of hardcoded URLs.
  • Write your own template tags as a returning function plus a printing wrapper, with a unique prefix.

Next, learn how to load your CSS and JavaScript properly in Enqueuing Styles and Scripts.