将变量传递给get_template_part
-
-
有[set_query_var`和`get_query_var` [关于同一个问题并使其起作用](https://wordpress.stackexchange.com/questions/270166/pass-a-variable-to-get-template-part),但是这是为了使用传递给WP_Query的$ args数组的值.可能对其他开始学习此方法的人有所帮助.Had [about the same question and got it to work](https://wordpress.stackexchange.com/questions/270166/pass-a-variable-to-get-template-part) with `set_query_var` and `get_query_var`, however this was for using the values of an `$args` array that is passed to a `WP_Query`. Might be helpful for other people starting to learn this.
- 0
- 2017-06-14
- lowtechsun
-
@Florian,请参阅https://wordpress.stackexchange.com/a/373230/54986,并在适当时标记为答案-现在这是一流的支持@Florian please see https://wordpress.stackexchange.com/a/373230/54986 and mark as an answer if appropriate - it's now a first-class supported thing
- 0
- 2020-08-18
- Selrond
-
13 个回答
- 投票数
-
- 2015-02-02
由于帖子通过
the_post()
(分别通过setup_postdata()
)设置其数据,因此可以通过API(get_the_ID()
,例如),假设我们正在遍历一组用户(如setup_userdata()
填充当前登录的用户的全局变量,对此任务没有帮助),并尝试显示每个用户的元数据:<?php get_header(); // etc. // In the main template file $users = new \WP_User_Query( [ ... ] ); foreach ( $users as $user ) { set_query_var( 'user_id', absint( $user->ID ) ); get_template_part( 'template-parts/user', 'contact_methods' ); }
然后,在我们的
wpse-theme/template-parts/user-contact_methods.php
文件中,我们需要访问用户ID:<?php /** @var int $user_id */ $some_meta = get_the_author_meta( 'some_meta', $user_id ); var_dump( $some_meta );
就是这样.
说明实际上恰好在您在问题中引用的部分上方:
但是,由
load_template()
间接调用的get_template_part()
将所有WP_Query
查询变量提取到加载的模板.原生PHP
extract()
函数"提取"变量(global $wp_query->query_vars
属性),并将每个部分放入其自己的变量中,该变量的名称与键的名称完全相同.换句话说:set_query_var( 'foo', 'bar' ); $GLOBALS['wp_query'] (object) -> query_vars (array) foo => bar (string 3) extract( $wp_query->query_vars ); var_dump( $foo ); // Result: (string 3) 'bar'
As posts get their data set up via
the_post()
(respectively viasetup_postdata()
) and are therefore accessible through the API (get_the_ID()
for e.g.), let's assume that we are looping through a set of users (assetup_userdata()
fills the global variables of the currently logged in user and isn't useful for this task) and try to display meta data per user:<?php get_header(); // etc. // In the main template file $users = new \WP_User_Query( [ ... ] ); foreach ( $users as $user ) { set_query_var( 'user_id', absint( $user->ID ) ); get_template_part( 'template-parts/user', 'contact_methods' ); }
Then, in our
wpse-theme/template-parts/user-contact_methods.php
file, we need to access the users ID:<?php /** @var int $user_id */ $some_meta = get_the_author_meta( 'some_meta', $user_id ); var_dump( $some_meta );
That's it.
The explanation is actually exactly above the part you quoted in your question:
However,
load_template()
, which is called indirectly byget_template_part()
extracts all of theWP_Query
query variables, into the scope of the loaded template.The native PHP
extract()
function "extracts" the variables (theglobal $wp_query->query_vars
property) and puts every part into its own variable which has exactly the same name as the key. In other words:set_query_var( 'foo', 'bar' ); $GLOBALS['wp_query'] (object) -> query_vars (array) foo => bar (string 3) extract( $wp_query->query_vars ); var_dump( $foo ); // Result: (string 3) 'bar'
-
仍然很棒still working great
- 1
- 2019-06-11
- middlelady
-
- 2015-02-04
hm_get_template_part函数>人造在这方面非常擅长,我一直都在使用它.
您致电
hm_get_template_part( 'template_path', [ 'option' => 'value' ] );
然后在模板中使用
$template_args['option'];
返回值.它可以缓存所有内容,尽管您可以根据需要将其删除.
您甚至可以通过传递
'return' => true
放入键/值数组./** * Like get_template_part() put lets you pass args to the template file * Args are available in the tempalte as $template_args array * @param string filepart * @param mixed wp_args style argument list */ function hm_get_template_part( $file, $template_args = array(), $cache_args = array() ) { $template_args = wp_parse_args( $template_args ); $cache_args = wp_parse_args( $cache_args ); if ( $cache_args ) { foreach ( $template_args as $key => $value ) { if ( is_scalar( $value ) || is_array( $value ) ) { $cache_args[$key] = $value; } else if ( is_object( $value ) && method_exists( $value, 'get_id' ) ) { $cache_args[$key] = call_user_method( 'get_id', $value ); } } if ( ( $cache = wp_cache_get( $file, serialize( $cache_args ) ) ) !== false ) { if ( ! empty( $template_args['return'] ) ) return $cache; echo $cache; return; } } $file_handle = $file; do_action( 'start_operation', 'hm_template_part::' . $file_handle ); if ( file_exists( get_stylesheet_directory() . '/' . $file . '.php' ) ) $file = get_stylesheet_directory() . '/' . $file . '.php'; elseif ( file_exists( get_template_directory() . '/' . $file . '.php' ) ) $file = get_template_directory() . '/' . $file . '.php'; ob_start(); $return = require( $file ); $data = ob_get_clean(); do_action( 'end_operation', 'hm_template_part::' . $file_handle ); if ( $cache_args ) { wp_cache_set( $file, $data, serialize( $cache_args ), 3600 ); } if ( ! empty( $template_args['return'] ) ) if ( $return === false ) return false; else return $data; echo $data; }
The
hm_get_template_part
function by humanmade is extremely good at this and I use it all the time.You call
hm_get_template_part( 'template_path', [ 'option' => 'value' ] );
and then inside your template, you use
$template_args['option'];
to return the value. It does caching and everything, though you can take that out if you like.
You can even return the rendered template as a string by passing
'return' => true
into the key/value array./** * Like get_template_part() put lets you pass args to the template file * Args are available in the tempalte as $template_args array * @param string filepart * @param mixed wp_args style argument list */ function hm_get_template_part( $file, $template_args = array(), $cache_args = array() ) { $template_args = wp_parse_args( $template_args ); $cache_args = wp_parse_args( $cache_args ); if ( $cache_args ) { foreach ( $template_args as $key => $value ) { if ( is_scalar( $value ) || is_array( $value ) ) { $cache_args[$key] = $value; } else if ( is_object( $value ) && method_exists( $value, 'get_id' ) ) { $cache_args[$key] = call_user_method( 'get_id', $value ); } } if ( ( $cache = wp_cache_get( $file, serialize( $cache_args ) ) ) !== false ) { if ( ! empty( $template_args['return'] ) ) return $cache; echo $cache; return; } } $file_handle = $file; do_action( 'start_operation', 'hm_template_part::' . $file_handle ); if ( file_exists( get_stylesheet_directory() . '/' . $file . '.php' ) ) $file = get_stylesheet_directory() . '/' . $file . '.php'; elseif ( file_exists( get_template_directory() . '/' . $file . '.php' ) ) $file = get_template_directory() . '/' . $file . '.php'; ob_start(); $return = require( $file ); $data = ob_get_clean(); do_action( 'end_operation', 'hm_template_part::' . $file_handle ); if ( $cache_args ) { wp_cache_set( $file, $data, serialize( $cache_args ), 3600 ); } if ( ! empty( $template_args['return'] ) ) if ( $return === false ) return false; else return $data; echo $data; }
-
包括1300行代码(来自github HM)到项目,以将一个参数传递给模板?在我的项目中无法做到这一点:(Include 1300 lines of code(from github HM) to the project to pass one parameter to a template? Can not do this in my project :(
- 1
- 2019-09-04
- Gediminas
-
您可以只将他上面粘贴的代码包括到您的functions.php中.You can just include the code he pasted above to your functions.php...
- 3
- 2019-11-15
- DokiCRO
-
- 2016-06-04
我环顾四周,发现了各种各样的答案.在本地级别,Wordpress确实允许在模板部件中访问变量.我确实发现结合使用include和locate_template确实可以在文件中访问变量作用域.
include(locate_template('your-template-name.php'));
I was looking around and have found a variety of answers. Its seems at a native level, Wordpress does allow for variables to be accessed in Template parts. I did find that using the include coupled with locate_template did allow for variables scope to be accessible in the file.
include(locate_template('your-template-name.php'));
-
使用`include`不会通过[themecheck](https://github.com/anhskohbo/wp-cli-themecheck).Using `include` won't pass [themecheck](https://github.com/anhskohbo/wp-cli-themecheck).
- 0
- 2017-06-14
- lowtechsun
-
我们真的需要像WP主题的W3C检查器之类的东西吗?Do we really need something that is like the W3C checker for WP Themes?
- 1
- 2019-08-15
- Fredy31
-
- 2017-08-05
// you can use any value including objects. set_query_var( 'var_name_to_be_used_later', 'Value to be retrieved later' ); //Basically set_query_var uses PHP extract() function to do the magic. then later in the template. var_dump($var_name_to_be_used_later); //will print "Value to be retrieved later"
我建议阅读有关PHP Extract()函数的信息.
// you can use any value including objects. set_query_var( 'var_name_to_be_used_later', 'Value to be retrieved later' ); //Basically set_query_var uses PHP extract() function to do the magic. then later in the template. var_dump($var_name_to_be_used_later); //will print "Value to be retrieved later"
I recommend to read about PHP Extract() function.
-
- 2016-09-11
我在当前正在从事的项目中遇到了同样的问题.我决定创建自己的小插件,该插件可让您使用新函数将变量更明确地传递给get_template_part.
以防万一,您可以在GitHub上找到它的页面:https://github.com/JolekPress/Get-Template-Part-With-Variables
这是它如何工作的示例:
$variables = [ 'name' => 'John', 'class' => 'featuredAuthor', ]; jpr_get_template_part_with_vars('author', 'info', $variables); // In author-info.php: echo " <div class='$class'> <span>$name</span> </div> "; // Would output: <div class='featuredAuthor'> <span>John</span> </div>
I ran into this same issue on a project I'm currently working on. I decided to create my own small plugin that allows you to more explicitly pass variables to get_template_part by using a new function.
In case you might find it useful, here's the page for it on GitHub: https://github.com/JolekPress/Get-Template-Part-With-Variables
And here's an example of how it would work:
$variables = [ 'name' => 'John', 'class' => 'featuredAuthor', ]; jpr_get_template_part_with_vars('author', 'info', $variables); // In author-info.php: echo " <div class='$class'> <span>$name</span> </div> "; // Would output: <div class='featuredAuthor'> <span>John</span> </div>
-
- 2020-08-03
从 5.5 开始,就有可能通过各种核心模板加载功能.
所有WordPress模板加载功能都将支持
$args
的附加参数,该参数允许主题作者将数据的关联数组传递给加载的模板.支持此新参数的函数是:get_header() get_footer() get_sidebar() get_template_part() locate_template() load_template()
与功能相关的任何钩子也会传递数据.
有关更多信息: https://make.wordpress.org/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/
Starting in 5.5, it will be possible to pass data to templates via the various core template-loading functions.
All of the WordPress template-loading functions will support an additional parameter of
$args
, which allows theme authors to pass along an associative array of data to the loaded template. The functions that support this new parameter are:get_header() get_footer() get_sidebar() get_template_part() locate_template() load_template()
Any hooks associated with the functions also pass along the data.
For more information: https://make.wordpress.org/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/
-
不幸的是,$ args参数没有通过extract()运行,因此您需要在模板中执行echo $ args ['foo']`.我希望也可以提取args.Unfortunately the `$args` parameter isn't run through `extract()` so you'll need to do `echo $args['foo']` in the template. I wish there was an option to extract the args too.
- 0
- 2020-08-17
- powerbuoy
-
- 2016-08-20
我喜欢 Pods 插件及其pods_view 函数.它的工作方式类似于djb的答案中提到的
_hm_get_template_part 函数.我使用附加功能(下面的代码中的 findTemplate
)首先在当前主题中搜索模板文件,如果找不到,它将在我插件的/中返回具有相同名称的模板模板
文件夹.这是我如何在插件中使用pods_view
的粗略想法:/** * Helper功能查找模板 */ 函数findTemplate($filename){ //首先在主题文件夹中查找 $template=locate_template($文件名); 如果(!$template){ //否则,请使用我们插件的/templates文件夹中的文件 $template=dirname(__ FILE__). '/templates/'. $filename; } 返回$template; } //从任一主题输出模板'template-name.php' //文件夹*或*我们插件的'/template'文件夹,传递两个本地 //变量在模板文件中可用 pods_view( findTemplate('template-name.php'), 数组( 'passed_variable'=&gt; $ variable_to_pass, 'another_variable'=&gt; $ another_variable, ) );
pods_view
也支持缓存,但是出于我的目的,我不需要它.有关函数参数的更多信息,请参见Pods文档页面.请参见pods_view 和带有Pod的部分页面缓存和智能模板部分.I like the Pods plugin and their pods_view function. It works similar to the
hm_get_template_part
function mentioned in djb's answer. I use an additional function (findTemplate
in the code below) to search for a template file in the current theme first, and if not found it returns the template with the same name in my plugin's/templates
folder. This is a rough idea of how I'm usingpods_view
in my plugin:/** * Helper function to find a template */ function findTemplate($filename) { // Look first in the theme folder $template = locate_template($filename); if (!$template) { // Otherwise, use the file in our plugin's /templates folder $template = dirname(__FILE__) . '/templates/' . $filename; } return $template; } // Output the template 'template-name.php' from either the theme // folder *or* our plugin's '/template' folder, passing two local // variables to be available in the template file pods_view( findTemplate('template-name.php'), array( 'passed_variable' => $variable_to_pass, 'another_variable' => $another_variable, ) );
pods_view
also supports caching, but I didn't need that for my purposes. More information about the function arguments can be found in the Pods documentation pages. See the pages for pods_view and Partial Page Caching and Smart Template Parts with Pods. -
- 2018-12-18
基于@djb的答案,使用的是人工制作的代码.
这是get_template_part的轻量级版本,可以接受args.这样,变量就可以在本地范围内限定于该模板.不需要
global
,get_query_var
,set_query_var
./** * Like get_template_part() but lets you pass args to the template file * Args are available in the template as $args array. * Args can be passed in as url parameters, e.g 'key1=value1&key2=value2'. * Args can be passed in as an array, e.g. ['key1' => 'value1', 'key2' => 'value2'] * Filepath is available in the template as $file string. * @param string $slug The slug name for the generic template. * @param string|null $name The name of the specialized template. * @param array $args The arguments passed to the template */ function _get_template_part( $slug, $name = null, $args = array() ) { if ( isset( $name ) && $name !== 'none' ) $slug = "{$slug}-{$name}.php"; else $slug = "{$slug}.php"; $dir = get_template_directory(); $file = "{$dir}/{$slug}"; ob_start(); $args = wp_parse_args( $args ); $slug = $dir = $name = null; require( $file ); echo ob_get_clean(); }
例如在
cart.php
中:<? php _get_template_part( 'components/items/apple', null, ['color' => 'red']); ?>
在
apple.php
中:<p>The apple color is: <?php echo $args['color']; ?></p>
Based on the answer from @djb using code from humanmade.
This is a lightweight version of get_template_part that can accept args. This way variables are scoped locally to that template. No need to have
global
,get_query_var
,set_query_var
./** * Like get_template_part() but lets you pass args to the template file * Args are available in the template as $args array. * Args can be passed in as url parameters, e.g 'key1=value1&key2=value2'. * Args can be passed in as an array, e.g. ['key1' => 'value1', 'key2' => 'value2'] * Filepath is available in the template as $file string. * @param string $slug The slug name for the generic template. * @param string|null $name The name of the specialized template. * @param array $args The arguments passed to the template */ function _get_template_part( $slug, $name = null, $args = array() ) { if ( isset( $name ) && $name !== 'none' ) $slug = "{$slug}-{$name}.php"; else $slug = "{$slug}.php"; $dir = get_template_directory(); $file = "{$dir}/{$slug}"; ob_start(); $args = wp_parse_args( $args ); $slug = $dir = $name = null; require( $file ); echo ob_get_clean(); }
For example in
cart.php
:<? php _get_template_part( 'components/items/apple', null, ['color' => 'red']); ?>
In
apple.php
:<p>The apple color is: <?php echo $args['color']; ?></p>
-
- 2020-08-18
用于模板加载功能的
$args
参数刚刚进入 WordPress 5.5" Eckstine" :将数据传递到模板文件
模板加载函数(get_header(),get_template_part()等)具有新的$ args参数.因此,现在您可以将整个阵列的数据传递给这些模板.
The
$args
parameter for template loading functions has just landed in WordPress 5.5 “Eckstine”:Passing data to template files
The template loading functions (get_header(), get_template_part(), etc.) have a new $args argument. So now you can pass an entire array’s worth of data to those templates.
-
- 2018-06-22
怎么样?
render( 'template-parts/header/header', 'desktop', array( 'user_id' => 555, 'struct' => array( 'test' => array( 1,2 ) ) ) ); function render ( $slug, $name, $arguments ) { if ( $arguments ) { foreach ( $arguments as $key => $value ) { ${$key} = $value; } } $name = (string) $name; if ( '' !== $name ) { $templates = "{$slug}-{$name}.php"; } else { $templates = "{$slug}.php"; } $path = get_template_directory() . '/' . $templates; if ( file_exists( $path ) ) { ob_start(); require( $path); ob_get_clean(); } }
通过使用
${$key}
,您可以将变量添加到当前函数作用域中. 快速简便地为我工作,并且不会泄漏或存储到全局范围中.How about this?
render( 'template-parts/header/header', 'desktop', array( 'user_id' => 555, 'struct' => array( 'test' => array( 1,2 ) ) ) ); function render ( $slug, $name, $arguments ) { if ( $arguments ) { foreach ( $arguments as $key => $value ) { ${$key} = $value; } } $name = (string) $name; if ( '' !== $name ) { $templates = "{$slug}-{$name}.php"; } else { $templates = "{$slug}.php"; } $path = get_template_directory() . '/' . $templates; if ( file_exists( $path ) ) { ob_start(); require( $path); ob_get_clean(); } }
By using
${$key}
you can add the variables into the current function scope. Works for me, quick and easy and its not leaking or stored into the global scope. -
- 2019-09-04
对于那些看起来很容易传递变量的人,可以将函数更改为包括以下内容:
include(locate_template('YourTemplate.php',false,false)));
然后您将能够使用在包含模板之前定义的所有变量,而无需通过模板,而且每个模板都无需通过.
贷方转到: https://mekshq.com/passing-variables-via-get_template_part-wordpress/
For ones who looks very easy way to pass variables, you can change function to include:
include( locate_template( 'YourTemplate.php', false, false ) );
And then you will be able to use all variables which are defined before you are including template without PASSING additionally each one for the template.
Credits goes to: https://mekshq.com/passing-variables-via-get_template_part-wordpress/
-
- 2020-09-02
更新
从 Wordpress 5.5起正确地 古怪 回答 > get_template_part()(参见更改日志)现在接受第三个参数array $args = array()
,它将在您的模板文件中以$args
形式提供.请参见以下示例:
$bar = 'bar'; // get helper-my-template.php get_template_part( 'template-parts/helper', 'my-template', array( 'foo' => $bar, // passing this array possible since WP 5.5 ) );
在您的模板文件中
例如 helper-my-template.php ,您现在可以像这样访问变量:
<?php /** * @var array $args */ $foo = $args['foo']; ?> <h1><?php echo $foo; ?></h1> <?php // will print 'bar' ?>
Update
As selrond correctly answered as of Wordpress 5.5 get_template_part() (see changelog) now accepts a third parameter
array $args = array()
, which will be available in your template file as$args
.See this example:
$bar = 'bar'; // get helper-my-template.php get_template_part( 'template-parts/helper', 'my-template', array( 'foo' => $bar, // passing this array possible since WP 5.5 ) );
In your template file
e.g. helper-my-template.php you can now access your variable like this:
<?php /** * @var array $args */ $foo = $args['foo']; ?> <h1><?php echo $foo; ?></h1> <?php // will print 'bar' ?>
-
- 2018-01-16
This is exact solution and it worked well. https://developer.wordpress.org/reference/functions/set_query_var/
WP Codex说:
但是如何在模板部分内
echo $my_var
?get_query_var($my_var)
对我不起作用.我已经看到了很多有关使用
locate_template
的建议.那是最好的方式吗?