Using get_template_part to include template files in WordPress

The get_template_part function in WordPress allows developers to include a specific template file within another template file. This can be useful for organizing and reusing code, making it easier to maintain and update a website. It also helps to keep the template files modular and easier to understand.

By using get_template_part, developers can separate different parts of the website, such as headers, footers, sidebars, and content sections, into their own template files. This makes it easier to make changes to specific parts of the website without having to modify the entire template file.

The get_template_part function helps to improve the organization and maintainability of WordPress themes, making it easier for developers to work with and customize templates.

Parameters Accepted by get_template_part Function

The get_template_part function accepts the following parameters:

  • $slug (string, required): The slug name for the generic template.
  • $name (string, optional, default value: null): The name of the specialized template.
  • $args (array, optional, default value: array()): Additional arguments passed to the template.

The function returns void on success, and false if the template does not exist.

Examples

How to include a specific template part in WordPress

Here’s an example of using get_template_part to include a specific template part in a WordPress theme:

<?php
get_template_part( 'template-parts/content', 'single' );
?>

This code snippet includes the template part content-single.php from the template-parts directory in the current theme.

How to include a fallback template part in WordPress

Here’s an example of using get_template_part to include a fallback template part in a WordPress theme:

<?php
get_template_part( 'content', 'none' );
?>

This code snippet includes the template part content-none.php from the current theme. If the file does not exist, it includes content.php instead as a fallback.

How to include a template part with variables in WordPress

Here’s an example of using get_template_part to include a template part with variables in a WordPress theme:

<?php
$post_format = get_post_format();
get_template_part( 'template-parts/content', $post_format );
?>

This code snippet includes the template part based on the post format, such as content-gallery.php or content-video.php, from the template-parts directory in the current theme.

Conclusion

The get_template_part function is an effective feature for organizing and reusing code in WordPress theme development. By breaking down templates into smaller, modular parts, developers can create more maintainable and flexible themes. This function also allows for easy customization and overrides, making it a valuable asset for creating dynamic and efficient WordPress themes.

Related WordPress Functions