get_template_part()
Searches for and connects the specified theme file (first check the file in the child theme, if there is one).
Like PHP include(), but no need to specify the path to the template.
This function is used to include the template part into a template, for example, to add a file responsible for: breadcrumbs, pagination, menu, etc.
// includes breadcrumbs.php from the current template's directory get_template_part( 'breadcrumbs' ); // includes breadcrumbs-footer.php from the current template's directory get_template_part( 'breadcrumbs', 'footer' );
If the specified file doesn't exist, nothing will happen.
Child themes
When using a child theme, this function will first try to include a file from the child theme, and if it isn't there, the file from the parent theme will be included.
This functionality allows users to override the parent's theme files in the child theme – create a file with the same name in the child theme. It's a suitable method because the modified files are persistent across updates of the parent theme.
Hooks from the function
Return
null|false
. Void on success, false if the template does not exist.
Usage
get_template_part( $slug, $name, $args );
- $slug(string) (required)
- The slug name for the generic template.
- $name(string|null)
- The name of the specialized template.
Default: null - $args(array)
- Additional arguments passed to the template.
Default: empty array
Examples
#1 Include loop.php file in child theme
The name of the parent theme is twentyten; the name of the child theme is twentytenchild. The below code will try to include the following files in the following order:
<?php get_template_part( 'loop', 'index' ); ?>
wp-content/themes/twentytenchild/loop-index.php
wp-content/themes/twentytenchild/loop.php
wp-content/themes/twentyten/loop-index.php
wp-content/themes/twentyten/loop.php
#2 Include navigation file (nav.php)
get_template_part( 'nav' ); // Navigation bar (nav.php) ?> get_template_part( 'nav', '2' ); // Navigation bar #2 (nav-2.php) ?> get_template_part( 'nav', 'single' ); // Navigation bar to use in single pages (nav-single.php) ?>
#3 Include files from theme sub-directories
get_template_part( 'inc/nav' ); // includes inc/nav.php
If you need to include inc/nav-single.php
:
get_template_part( 'inc/nav', 'single' ); // or: get_template_part( 'inc/nav-single' );
In the first case, the inc/nav-single.php
file will be included first, and if it does not exist then inc/nav.php
. In the second, only inc/nav-single.php
.
#4 Parameter Transmission
$params = [ 'param1' => 'hello', 'param2' => [ 1, 2 ] ]; get_template_part( 'inc/nav-single.php', 'single', $params );
Now in the file inc/nav-single.php
the specified parameters are in the $args
variable. Example code of such a file:
<?php echo $args['param1']; //> hello
Changelog
Since 3.0.0 | Introduced. |
Since 5.5.0 | A return value was added. |
Since 5.5.0 | The $args parameter was added. |