WordPressget_template_part()

Introduction

The purpose of this function is to standardize the way import partials or components of a theme into the main theme template. You could use a standard PHP SSI (server side includes), however, there are some benefits to using get_template_part(). Using this function reduces errors prone to less experienced developers trying to identify fully qualified path on the server.Also, it fails gracefully when files don't exist, and handles a custom hierarchy fallback system aka "fuzzy template searching".

Syntax

  • get_template_part( $slug )
  • get_template_part( $slug, $name )

Parameters

ParameterDetails
$slug(string) The slug name of the custom template.
$name(string) The name of the specialized template. Optional

Including a custom template

<?php get_template_part( 'foo' ); ?>

Includes

../wp-content/themes/your-theme-slug/foo.php

Including a custom template with a dash-separated filename

<?php get_template_part( 'foo','bar' ); ?>

Includes

../wp-content/themes/your-theme-slug/foo-bar.php

Including a custom template from inside a directory

<?php get_template_part( 'dir/foo' ); ?>

Includes

../wp-content/themes/your-theme-slug/dir/foo.php

Including a custom template with a dash-separated filename located inside a directory

<?php get_template_part( 'dir/foo', 'bar' ); ?>

Includes

../wp-content/themes/your-theme-slug/dir/foo-bar.php

Passing variable to custom template scope

<?php 
set_query_var( 'passed_var', $my_var ); 
get_template_part( 'foo', 'bar' );
?>

Access it in foo-bar.php

<?php echo $passed_var; ?>