Get_Template_Part - Why we Use It

Get_template_part() – Organizing WP Theme Architecture

Recently, I’ve received several support requests regarding the get_template_part() function from agencies developing child themes based on a Nimbus Theme.

There seems to be confusion about how this function works and why we’ve chosen to implement it in our themes. This post will look at what this important function offers and how it simplifies and enhances WordPress theme architecture.

About the get_template_part Function

Those of you who delve into WordPress theme development or child-theming likely understand that each theme is comprised of a set of minimum core templates including a stylesheet called style.css and an index.php file that organizes the display of content. In addition to these minimums, the WordPress application checks for higher-level templates that fulfill specific display roles. A higher-level example is an archive.php file that organizes the display of content on an archive page like a category feed or a collection of similarly tagged posts.

Some parts of a website tend to be universal, so WordPress offers a handful of special “include” tags like get_header(), get_footer(), and get_sidebar(). But what about non-universal template sections that will be used multiple times or will be conditionally called upon depending on the business logic of the theme? For this, we have the get_template_part() function.

Get_template_part() acts as a PHP include() or require(), but with a few extra bells and whistles. You can actually follow the function paths backward in the core (see below) to the load_template() function where you find the require() and require_once() functions being used.

/wp-includes/general-template.php

function get_template_part( $slug, $name = null ) {
        do_action( "get_template_part_{$slug}", $slug, $name );
        $templates = array();
        $name = (string) $name;
        if ( '' !== $name )
                $templates[] = "{$slug}-{$name}.php";
        $templates[] = "{$slug}.php";
        locate_template($templates, true, false);
}

/wp-includes/template.php

function locate_template($template_names, $load = false, $require_once = true ) {
        $located = '';
        foreach ( (array) $template_names as $template_name ) {
                if ( !$template_name )
                        continue;
                if ( file_exists(STYLESHEETPATH . '/' . $template_name)) {
                        $located = STYLESHEETPATH . '/' . $template_name;
                        break;
                } else if ( file_exists(TEMPLATEPATH . '/' . $template_name) ) {
                        $located = TEMPLATEPATH . '/' . $template_name;
                        break;
                }
        }
        if ( $load && '' != $located )
                load_template( $located, $require_once );
        return $located;
}

/wp-includes/template.php

function load_template( $_template_file, $require_once = true ) {
        global $posts, $post, $wp_did_header, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID;
        if ( is_array( $wp_query->query_vars ) )
                extract( $wp_query->query_vars, EXTR_SKIP );
        if ( $require_once )
                require_once( $_template_file );
        else
                require( $_template_file );
}

In addition to harnessing PHP require(), get_template_part() also provides a framework for template naming that follows the conventions used in other core WordPress include tags like get_header(), get_sidebar(), etc. This framework allows for the use of both a $slug variable and a $name variable such that you might have a $slug with many alternate $name versions or with none at all.

get_template_part( $slug );
get_template_part( $slug, $name_1 ); 
get_template_part( $slug, $name_2 )

Get_template_part also degrades sanely. If you request the partial: get_template_part( 'slug', 'name' ); and the file slug-name.php does not exist, the application will search for slug.php. If that also is not available, it will respond with no result, but it will not spin off an error the way require() will.

Finally, get_template_part() knows to look for child themes. This means you can override a parent theme Partial by simply including a modified copy in the child theme.

How We Use It At Nimbus Themes

There are four ways that we use template partials at Nimbus Themes:

  • Breaking out snippets of code or markup that will be used repeatedly.
  • Removing clutter from higher-level templates.
  • Providing views that can be used conditionally.
  • Better child theming.

Breaking out snippets of code or markup that will be used repeatedly.

When I first began coding themes for the Nimbus Themes collection, I had a tendency to bloat the template structure unnecessarily. I might create both a tag.php and a category.php when both could be handled by archive.php. A side effect of this was including elements like pagination on multiple templates. When a bug would come to my attention that affected this element, I would need to track it down on all the applicable templates. This became increasingly challenging as the complexity of the themes increased.

By breaking these elements into template partials and including them via the get_template_part() function, the need to track and update in multiple locations was dispelled. Editing the partial would now fix the bug in all the higher level templates where the part was in use.

Removing clutter from higher-level templates.

Template partials are a great way to keep your top-level templates clean and easy to read. An example of this is the index.php file in our Soliloquy Theme. Rather than create any secondary templates like archives.php, page.php, or search.php, I let everything default back to the index.php template which included the header, footer, and a loop.php partial.

get_header();
get_template_part( 'parts/loop');    
get_footer(); 

This keeps the main template directory clean and pushes everything to the loop.php partial, where we sort through and organize the display.

Providing views that can be used conditionally.

Continuing with the example from the last section, we can look at the loop.php file in the Soliloquy theme, where we sort out which display layout to use depending on the class of content. Again, this is a perfect application for partials.

if (is_single()) {
     get_template_part( 'parts/content', 'single');
} else if (is_page()) {
     get_template_part( 'parts/content', 'page');
} else {
     get_template_part( 'parts/content', 'blog');
}

Note that this is a simple version, but you could target a variety of conditions, like whether or not a post has a featured image attachment or depending on the age of the content.

Better child theming.

While I’m including this topic last, it is by no means a minor concern. An issue we ran into with customers repeatedly was their creating a child theme that modified a higher level template which was subsequently modified in a theme update. Unfortunately, this would mean that the effects of the update would not be reflected on their theme even if they had only made a small edit to one element in a template that included many elements.

By using the get_template_part function to include all the elements individually, our customers are able to modify one element at a time without having to worry about losing out on the benefits of regular theme updates.

Conclusion

Overall, the get_template_part function offers a way to better organize themes and create better compatibility with core features and child themes.

I don’t imagine that I’ve found the perfect approach to using template partials, but I’ve found a system that works well for my team and clients. I’d also love to hear from other developers about how you use partials.

In closing, I hope this post provides some clarity to our customers about partials and what value they offer in our themes.

This post may contain affiliate links, which means Nimbus Themes may receive compensation if you make a purchase using these links.

Written exclusively for

Nimbus Themes Publishing Logo

About the Author

Evan Scoboria is the co-founder, and developer at Shea Media LLC, the team behind Nimbus Themes, this magazine, and a bunch of very happy clients. He co-founded Shea Media with his wife Kendall in 2009. Evan enjoys hunting, fishing, code, cycling, and most of all WordPress!

Read all posts

1 Comment

  1. Asen Avatar

    Asen

    December 1, 2015 at 10:35 am

    Thanks for your explanation. But, how do I allow a unique description for each category and tag? There is neither an archive.php nor the category.php where I can put the code in. Can you help?

    Reply

Leave a Reply

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