How to Use WordPress get_template_part() for Theme Development?

wordpress get_template_part()

For developers aiming to streamline the WordPress theme development and maintain cleaner code, the WordPress get_template_part() function is an indispensable tool. This function is a key part of modular design principles and helps reduce code redundancy, meaning easier updates and maintenance.

WordPress experts use this function to load reusable template snippets across different parts of a WordPress theme. It promotes efficiency and adherence to the DRY (Don’t Repeat Yourself) principle.

This blog explores the basics of WordPress get_template_part(), from the ‘Why’ to the ‘How’, and of course, the best practices. Let’s begin.

What is WordPress get_template_part()?

Writing clean and maintainable code is a fundamental aspect of WordPress theme development. Instead of duplicating the same template code across multiple files, WordPress provides a built-in function to streamline this process, i.e. get_template_part().

This function enables developers to include reusable template sections dynamically, reducing redundancy and improving code organization.

Syntax: get_template_part( $slug, $name = null );

  • $slug (required) – The base name of the template file (e.g., ‘content’, ‘header’, ‘footer’).
  • $name (optional) – A specific variation of the template part (e.g., ‘single’, ‘archive’).

The get_template_part() is a cornerstone of efficient and maintainable WordPress theme development. It encourages code reuse, improves organization, and is essential for creating themes that are child theme friendly.

Why Use WordPress get_template_part()?

Efficient theme development goes beyond just writing functional code–it requires a structured approach that promotes reusability and maintainability. Instead of manually copying and pasting the same sections across different template files, get_template_part() offers a cleaner way to manage reusable components.

Using WordPress get_template_part() instead of directly including files with include or require has several advantages:

  1. Code Reusability – Encourages modular design by allowing you to reuse components across multiple templates.
  2. Improved Maintainability – Makes it easier to update a single file without affecting multiple templates.
  3. Follows WordPress Standards – Ensures compatibility with WordPress’s best practices and allows child themes to override template parts.
  4. Enhances Theme Flexibility – Helps in creating different versions of a template dynamically.

Essentially, get_template_part() promotes efficiency, maintainability, flexibility, and adherence to best practices. It’s a fundamental tool for creating robust and scalable WordPress themes.

Want help with advanced WordPress functions on your site?

How Does WordPress get_template_part() Works?

Understanding how WordPress locates and loads template parts is key to using get_template_part() effectively. When this function is called, WordPress follows a specific hierarchy to determine which template file to include.

This ensures that the correct version of a template is loaded based on the context, such as a specific post type or content format. Knowing this process helps developers structure their theme files efficiently and avoid unnecessary duplication.

When calling get_template_part(), WordPress searches for template files in the following order:

  1. slug-name.php (e.g., content-single.php)
  2. slug.php (e.g., content.php)
  3. Falls back to the default WordPress template hierarchy

If none of these files exist, no content is loaded.

Example 1: Loading a Standard Template Part

  • To include a generic content template: get_template_part(‘content’);
  • This looks for content.php inside the active theme directory.

Example 2: Loading a Specific Template Variation

  • To load content-single.php for single posts: get_template_part(‘content’, ‘single’);
  • This checks for content-single.php first. If it doesn’t exist, it falls back to content.php.

With WordPress’s built-in template hierarchy, get_template_part() ensures that the most appropriate template file is loaded while providing a fallback mechanism if a specific version isn’t available.

If you want greater flexibility in theme customization while keeping the codebase well-organized and easy to maintain, get our dedicated WordPress development services.

Where to Use WordPress get_template_part() in Your Theme?

get_template_part() is a versatile WordPress function that can be used in various scenarios to improve theme structure and maintainability. From loading different content layouts to managing headers, footers, and sidebars, it helps developers create flexible and reusable template parts.

Loading Post Content

To load content based on the post type: get_template_part(‘template-parts/content’, get_post_type());

For a post, this loads template-parts/content-post.php. For a page, it loads template-parts/content-page.php.

Customizing Headers and Footers

Instead of using get_header() and get_footer(), you can use:

get_template_part('template-parts/header', 'custom');
get_template_part('template-parts/footer', 'alternate');

This loads template-parts/header-custom.php and template-parts/footer-alternate.php.

Using get_template_part() with Loops

You can use it inside loops to display different content formats:

while ( have_posts() ) : the_post();
    get_template_part('template-parts/content', get_post_format());
endwhile;

This loads content-video.php for video posts, content-gallery.php for galleries, etc.

By integrating get_template_part() into different areas of a theme, WordPress developers can streamline their workflow and ensure consistency across templates. Its adaptability makes it an essential tool for efficient theme development.

Best Practices for Using get_template_part() in WordPress

Using WordPress get_template_part() effectively goes beyond just including template files–it requires thoughtful organization and adherence to best practices. Structuring template parts properly, naming files intuitively, and ensuring compatibility with child themes can make a significant difference in theme maintainability.

Organize Template Parts Properly

Structure your template parts directory logically. Group related components into subfolders (e.g., partials/headers, partials/footers). This keeps your theme directory clean and makes it easier to locate specific template parts when needed for maintenance or updates.

get_template_part('template-parts/content', 'page');

Use Meaningful Slugs and Names

Opt for descriptive slugs and names for your template parts. Instead of generic names like part1.php, use names like content-sidebar.php or header-main.php. This improves code readability and makes it clear what each template part contains without opening the file.

For example, instead of get_template_part(‘part’), use descriptive names like get_template_part(‘template-parts/content’, ‘archive’).

Ensure Compatibility with Child Themes

Leverage the $name parameter in get_template_part() to allow child themes to easily override specific variations of a template part. For example, use get_template_part(‘post’, get_post_format()) so child themes can provide post-video.php.

Use locate_template() for better compatibility.

locate_template(array('template-parts/content-single.php', 'template-parts/content.php'), true);

Combine with if Statements for Dynamic Loading

Use conditional tags and if statements to load template parts dynamically based on specific conditions, like user roles or page types. This allows for flexible content display without creating numerous template files for every minor variation.

if ( is_single() ) {
    get_template_part('template-parts/content', 'single');
} else {
    get_template_part('template-parts/content', 'archive');
}

Avoid Overloading with Too Many Variations

While using $name is beneficial, avoid creating an excessive number of highly specific template part variations. Aim for a balance between reusability and specificity to prevent your theme directory from becoming overly complex and difficult to manage.

A well-structured approach ensures that template parts remain efficient, reusable, and adaptable to future changes without unnecessary complexity. For that, you can consult with our professional WordPress development company.

include vs. get_template_part(): Which WordPress Function to Use?

Choosing between PHP’s include (or require) and WordPress get_template_part() boils down to context and WordPress best practices. While both insert one file into another, get_template_part() is tailored for theme development, offering key advantages.

include/require are standard PHP functions for direct file inclusion. They’re unaware of WordPress’s theme structure and child themes. Using them directly in themes can hinder child theme customization and maintainability.

<?php

// In your plugin's main file

function my_plugin_settings_page() {
    // ... some code ...
    include( plugin_dir_path( __FILE__ ) . 'includes/my-plugin-settings.php' );
    // ... more code ...
}

Conversely, WordPress get_template_part() is a specific function designed for theme template files. It’s theme hierarchy aware, checking the child theme first, crucial for overrides. It promotes modularity and uses slugs/names for structured WordPress template part file retrieval.

<?php

// In your theme's single.php file

if ( get_the_author_meta( 'description' ) ) :
    get_template_part( 'template-parts/author-bio' );
endif;

?>

Use get_template_part() for including template files within WordPress themes. This ensures child theme compatibility and better organization. Use include/require in plugins or for including non-theme specific PHP files.

In essence, for theme development, get_template_part() is the preferred choice due to its WordPress-centric features, especially its support for child themes.

Need a Custom WordPress Website? We Can Help!

FAQs on WordPress get_template_part()

Can child themes override WordPress template parts included with get_template_part()?

Yes, this is one of the key benefits. WordPress will first look for the template part file in the child theme’s directory using the provided $slug and $name. If it’s not found there, it will then look in the parent theme’s directory.

How can I pass variables to a template file when using get_template_part()?

Since get_template_part() does not support direct variable passing, you can use set_query_var() before calling the function or use include locate_template().

What happens if the specified template file doesn’t exist?

If WordPress cannot find the specified template part, it simply does nothing—no error is thrown, but no content is displayed.

Can get_template_part() be used for headers, footers, and sidebars?

Although get_template_part() can load these components, WordPress provides dedicated functions like get_header(), get_footer(), and get_sidebar() for better flexibility.

Let’s Conclude

A well-structured WordPress theme relies on modular design, and get_template_part() plays a crucial role in achieving that. By allowing developers to reuse WordPress template sections efficiently, it simplifies maintenance, improves organization, and enhances overall flexibility.

Whether you’re building custom content layouts, managing headers and footers, or streamlining your theme’s structure, this function ensures a cleaner and more scalable approach.

For more help with ensuring a cleaner codebase for your theme and overall website, connect with our WordPress professionals today!

author
Chinmay Pandya is an accomplished tech enthusiast specializing in PHP, WordPress, and Laravel. With a solid background in web development, he brings expertise in crafting innovative solutions and optimizing performance for various projects.

Leave a comment