get_template_part()
概述
get_template_part() 是 WordPress 核心函数,用于在主题模板中加载可重用的模板部分。它支持子主题覆盖父主题的模板部分,并允许传递参数到模板中。
关键要点
- 函数用于加载模板部分,支持通过 $slug 和 $name 参数指定模板文件,例如 {slug}-{name}.php 或 {slug}.php。
- 从 WordPress 5.5 版本开始,新增 $args 参数,可直接传递数组数据到模板部分,无需依赖全局变量或 set_query_var()。
- 函数使用 require 而非 require_once,因此同一模板部分可被多次包含。
- 如果模板文件不存在,函数返回 false(自 WordPress 5.5 后),否则返回 void;失败时静默处理。
- 支持两个动作钩子:get_template_part_{$slug} 和 get_template_part,允许开发者在加载模板前后执行自定义代码。
- 适用于经典主题,块主题应使用 block_template_part()。
代码示例
// 基本用法
get_template_part( 'content', 'page' );
// 传递参数(WordPress 5.5+)
$args = array( 'key' => 'value' );
get_template_part( 'template-part', 'name', $args );
// 在模板部分中访问参数
echo $args['key'];注意事项
- 避免使用 extract() 处理 $args,因为不符合 WordPress PHP 编码标准。
- 模板文件搜索遵循子主题优先原则,例如子主题的 loop-index.php 优先于父主题的 loop.php。
- 可通过文件夹路径指定模板,如 get_template_part( 'template-parts/content', 'page' ) 加载 template-parts/content-page.php。
Loads a template part into a template.
Description
Provides a simple mechanism for child themes to overload reusable sections of code in the theme.
Includes the named template part for a theme or if a name is specified then a specialized part will be included. If the theme contains no {slug}.php file then no template will be included.
The template is included using require, not require_once, so you may include the same template part multiple times.
For the $name parameter, if the file is called “{slug}-special.php” then specify “special”.
Parameters
$slugstringrequired-
The slug name for the generic template.
$namestring|nulloptional-
The name of the specialized template.
Default:
null $argsarrayoptional-
Additional arguments passed to the template.
Default:
array()
Source
function get_template_part( $slug, $name = null, $args = array() ) {
/**
* Fires before the specified template part file is loaded.
*
* The dynamic portion of the hook name, `$slug`, refers to the slug name
* for the generic template part.
*
* @since 3.0.0
* @since 5.5.0 The `$args` parameter was added.
*
* @param string $slug The slug name for the generic template.
* @param string|null $name The name of the specialized template
* or null if there is none.
* @param array $args Additional arguments passed to the template.
*/
do_action( "get_template_part_{$slug}", $slug, $name, $args );
$templates = array();
$name = (string) $name;
if ( '' !== $name ) {
$templates[] = "{$slug}-{$name}.php";
}
$templates[] = "{$slug}.php";
/**
* Fires before an attempt is made to locate and load a template part.
*
* @since 5.2.0
* @since 5.5.0 The `$args` parameter was added.
*
* @param string $slug The slug name for the generic template.
* @param string $name The name of the specialized template
* or an empty string if there is none.
* @param string[] $templates Array of template files to search for, in order.
* @param array $args Additional arguments passed to the template.
*/
do_action( 'get_template_part', $slug, $name, $templates, $args );
if ( ! locate_template( $templates, true, false, $args ) ) {
return false;
}
}
Hooks
- do_action( ‘get_template_part’, string $slug, string $name, string[] $templates, array $args )
-
Fires before an attempt is made to locate and load a template part.
- do_action( “get_template_part_{$slug}”, string $slug, string|null $name, array $args )
-
Fires before the specified template part file is loaded.
Skip to note 17 content
Vinobe
Passing variables after WordPress 5.5 update
======================================
When calling function
get_template_part( 'template-part', 'name', array( 'key' => 'value', 'key2' => 'value2' ) );In your template part
var_dump( $args ); // Everything echo $args['key']; // Specific valuesSkip to note 18 content
Codex
Using with theme subfolders
To use this function with subfolders in your theme directory, simply prepend the folder name before the slug. For example, if you have a folder called “partials” in your theme directory and a template part called “content-page.php” in that sub-folder, you would use
get_template_part()like this:Skip to note 19 content
pcarvalho
the old codex had this entry about “Passing Variables to Template”
Because the template is being required, it will not have access to any variables you define within the calling theme’s PHP code, unless you explicitly declare them as global.
However, load_template() , which is called indirectly by get_template_part() extracts all of the WP_Query query variables, into the scope of the loaded template. So you can use set_query_var() to make your variable available to the template part.
// You wish to make $my_var available to the template part at `content-part.php` set_query_var( 'my_var', $my_var ); get_template_part( 'content', 'part' );Skip to note 20 content
Codex
Using loop.php in child themes
Assuming the theme folder is
wp-content/themes, that the parent theme is twentyten, and the child theme is twentytenchild, then the following code —will do a PHP
require()for the first file that exists among these, in this priority:wp-content/themes/twentytenchild/loop-index.php
wp-content/themes/twentyten/loop-index.php
wp-content/themes/twentytenchild/loop.php
wp-content/themes/twentyten/loop.php
Skip to note 21 content
Codex
Navigation
Adding a navigation bar to theme using a generic
nav.phptemplate file:Skip to note 22 content
captaincainer
A simple example of how to use the
$argsparameter in WordPress 5.5 in your template parts.'hello world' ); get_template_part( 'template-parts/file', 'name', $args ); // template-parts/file-name.phpIn your template part.
<h2></h2>Output:
<h2>hello world</h2>Skip to note 23 content
Andy Macaulay-Brook
Sometime since January 2019, the function has changed to return false if no template file is found. This isn’t noted in the code comments or changelog. The note that the function fails silently is no longer correct.
This now makes it easy for plugins to provide a template fallback (or allow a template override, depending on your perspective) like this:
if ( false === get_template_part( $slug, $name, $args ) ) { // default output }Skip to note 24 content
Selrond
Get a specific file
Although this kind of defeats the purpose of this function, it’s also possible to load a specific template file with it. All you have to do is use just one argument:
will include
layout.phpfrom template-parts subdirectory placed in the root of your theme folder.Skip to note 25 content
jabbadu
Since WP 5.5 the $args parameter is used to pass variables through the template.
/* content.php */Skip to note 26 content
Ahmad Karim
You can also access the template variables in your template part file by doing this:
extract( $args ); echo $variable1; echo $variable2;Your
get_template_partwill look something like this:$args = array( 'variable1' => '$variable1 Value', 'variable2' => '$variable2 Value', ); get_template_part( 'template-parts/template-part-file', null, $args );– Keep in mind that the third argument
$argshas been added since version 5.5extract().Skip to note 27 content
theaquarium
Please note that this function only works for Classic WordPress themes. To print a template part in a Block theme, use block_template_part() instead.
Skip to note 28 content
pixelstorm
Use a boolean in the $args
true ) ); ?>//show the btn on the template partSkip to note 29 content
Muhammad Jawad Abbasi
get_template_part(foldername/filename without .php extension)
Create a folder in the theme main directory
Folder name “template-parts” then add two .php files in “template-parts” folder loginuser.php and nonloginuser.php
If user login show loginuser.php file content
If the user do not login show nonloginuser.php file content
Note: Use any folder & files name above I have use random folder name and files name.
Skip to note 30 content
luboslives
If your web server is using ModSecurity, it will likely block attempts to inline SVGs using a PHP method like
file_get_contents(). You can useget_template_part()to inline SVGs.icon.svgbecomesinline-icon.svg.phpget_template_part( 'images/inline', 'icon.svg' );At the time of writing, this works to get around the default OWASP rule set for ModSecurity. Not tested with other rule sets.
Skip to note 31 content
Felipe Marcos
Passing variables to get_template_part()
It’s not possible to pass variables to a template loaded via get_template_part() . I came up with a workaround that doesn’t rely on global variables for it to work.
/* functions.php */ function get_custom_template($file = '', $arguments = []) { extract($arguments); include( locate_template( $file .'.php', false, false ) ); }/* loop.php */ while( have_posts() ): the_post(); get_custom_template( 'content', [ 'is_featured' => true ]); endwhile;Now, when we try to use $is_featured, it will be available to content.php only.
/* content.php */ the_title(); the_content(); var_dump($is_featured); // trueSkip to note 32 content
shahriyar.modami
How to passing variables to get_template_part() correctly: WordPress + 5.5
1- Setup variable
$data = array( 'location' => 'slider', 'number' => 3 );2- Passing variable to get_template_part
get_template_part( 'templates/slider', 'full', $data ); //templates/slider-full.php3- get data in part of template
global $data; //dont forget use globally print_r($data); // output: array('location' => 'slider', 'number' => 3)