get_template_part used to load a part of a template file into the template and helps divide the large file into smaller templates.
That’s the beauty of get_template_part. What you can do is save small chunks of code in a separate folder that can be used on multiple templates and then load those reusable components.
The template is included using PHP require which lets import same file multiple times on a page.
Syntax
get_template_part( $slug, $name, $args )
Where
- $slug is the slug name of the template and it’s a required parameter.
- $name is name for the template, it is an optional argument. By default it’s null.
- You can pass additional arguments using $args such as variables and values. By default an empty array will be passed.
What if the template file doesn’t exist?
Nothing will be imported in that case. There won’t be any errors either.
How to use get_template_part?
In get_template_part function, add the folder name and then the template page slug (without the .php extension).
You can have content.php or content-page.php. Both of them works!
Example
If you have this folder structure…
theme/
|-- partials/
| |-- content.php
|-- page.php
…then you can import the content.php from partials like this:
get_template_part( 'partials/content', 'page' );
How to pass variables via get_template_part?
get_template_part(
'partials/content',
'page',
array(
'key' => 'value',
'title' => 'Title',
)
);
How to get variables passed via get_template_part?
In your content.php file, you’d get the variables like this:
$key = $args['key'];
$title = $args['title'];
//use them anywhere in your file now
If you’re not sure what variables are passed, just dump everything and go from there:
var_dump( $args );
array examples functions get_template_part require template