多年来,希望将数据传递到模板文件的主题开发人员不得不使用不太理想的解决方法。这包括使用全局变量、 set_query_var()
、include( locate_template() )
模型或自己版本的 get_template_part()
等等。
从WordPress 5.5开始 ,模板加载功能将允许使用$args
参数将其他参数传递给匹配的模板文件。
受影响的函数
为了提供适当的上下文,相关的动作挂钩也已更新为传递此新$args
参数。
get_header
get_footer
get_sidebar
get_template_part_{$slug}
get_template_part
注意: get_search_form()
从[44956]开始,已经接受并将其他参数传递给搜索表单模板。但是,该$args
参数是在与上述挂钩同时添加的。它们是:
pre_get_search_form
(行动)search_form_format
(过滤)get_search_form
(过滤)
示例
<?php
get_template_part(
'foo',
null,
array(
'class' => 'user',
'arbitrary_data' => array(
'foo' => 'baz',
'bar' => true,
),
...
)
);
在上面的示例中,可以通过本地范围的 $args
变量在模板 foo.php
内访问get_template_part()
通过$args
变量传递的其他数据。
<?php
// Example foo.php template.
// Set defaults.
$args = wp_parse_args(
$args,
array(
'class' => '',
'arbitrary_data' => array(
'foo' => 'fooval',
'bar' => false,
),
...
)
);
?>
<div class="widget <?php echo esc_html_class( $args['class'] ); ?>">
<?php echo esc_html( $args['arbitrary_data']['foo'] ); ?>
</div>
注意:使用此新功能时,任何当前包含$args
变量的模板文件都应注意。对已加载的模板文件的$args
任何修改将覆盖使用上述函数传递的所有值。
该功能请求是8年前提交的,大家都久等了,感谢开发人员的努力!
要了解更多信息,请查看#21676。
来源:
https://www.wpdaxue.com/passing-arguments-to-template-files-in-wordpress-55.html