在Wordpress中,如何使用get_template_part_{slug}更改get_template_part的参数?

问题描述 投票:0回答:1

我试图将逻辑排除在我的模板之外。我想将变量传递到模板部分,因此在 single.php 中我有:

get_template_part('template-parts/the-slug', null, ['example' => 1]);

在functions.php中我有这个函数并将其添加到get_template_part_template-parts/the-slug中,如下所示:

add_action('populate', 'get_template_part_template-parts/the-slug');

public function populate( $name, $template, $args ){
   print_r($args);
   $args['another var'] = 2; 
}

所以该函数可以正常触发。我的问题是我想在 populate() 中设置 $args (或其他一些变量)以使它们在模板部分中可用。这可能吗?

wordpress templates variables hook
1个回答
0
投票

首先,get_template_part()本身不支持将变量传递给包含的模板文件。在 single.php 文件中传递给 get_template_part() 的第三个参数实际上在 WordPress 的 get_template_part() 默认实现中没有执行任何操作。

其次,add_action()不用于扩展像get_template_part()这样的函数的功能。相反,add_action() 用于将函数链接到 WordPress 中触发的特定操作。 “populate”操作不是默认的 WordPress 操作,并且与 get_template_part() 无关。

您可以使用 set_query_var() 使变量可用于模板部分。

© www.soinside.com 2019 - 2024. All rights reserved.