WordPress get_template_part传递变量

Was*_*and 4 variables wordpress

有没有一种方法可以在wordpress中将变量传递给get_template_part():

<?php get_template_part( 'element-templates/front', 'top' ); ?>
<?php get_template_part( 'element-templates/front', 'main' ); ?>
Run Code Online (Sandbox Code Playgroud)

在front-top.php和front-main.php中(以上所述),我需要访问数字变量(每个部分一个不同的变量)。有没有一种方法可以将变量传递给上面的每个调用?

谢谢

小智 6

我正在回答这个问题,因为这是Google在此问题上获得的最高成绩之一。

是的-您可以将变量传递给get_template_part()

在您的主题中:

<?php
set_query_var('my_var_name', 'my_var_value');
get_template_part('blocks/contact');
?>
Run Code Online (Sandbox Code Playgroud)

在模板部分:

<?php
$newValue = get_query_var('my_var_name');
if ( $newValue ) {
// do something
}
?>
Run Code Online (Sandbox Code Playgroud)


Nat*_*son 6

核心get_template_part()函数不支持传递变量。它只接受两个参数,slug 和 name。虽然没有针对此问题的内置解决方案,但最好的方法是创建一个密切模仿get_template_part()来处理它的函数。

通常我会创建一个函数,它只接受模板文件的名称和我想作为数组传入的变量。但是,在您的示例中,您已经使用了两个参数,get_template_part()这意味着您需要一个稍微复杂的函数。我将在下面发布两个版本。

简化版 - 名称(slug)和数据

function wpse_get_partial($template_name, $data = []) {
    $template = locate_template($template_name . '.php', false);

    if (!$template) {
        return;
    }

    if ($data) {
        extract($data);
    }

    include($template);
}
Run Code Online (Sandbox Code Playgroud)

用法示例: wpse_get_partial('header-promotion', ['message' => 'Example message']);

这会加载一个文件名为header-promotion.php$message它可用内部。由于第二个参数是一个数组,因此您可以根据需要传入任意数量的变量。

get_template_part 的副本 - 添加第三个参数

如果您不需要这两者,$slug并且$name在调用 时get_template_part(),您可能需要简化版本。对于那些这样做的人,这是更复杂的选择。

function wpse_get_template_part($slug, $name = null, $data = []) {
    // here we're copying more of what get_template_part is doing.
    $templates = [];
    $name = (string) $name;

    if ('' !== $name) {
        $templates[] = "{$slug}-{$name}.php";
    }

    $templates[] = "{$slug}.php";

    $template = locate_template($templates, false);

    if (!$template) {
        return;
    }

    if ($data) {
        extract($data);
    }

    include($template);
}
Run Code Online (Sandbox Code Playgroud)

用法示例: wpse_get_template_part('header-promotion', 'top', [$message => 'Example message']);

这两个函数都不是get_template_part(). 为简单起见,我跳过了核心函数使用的所有额外过滤器。

全局变量或查询变量怎么样

  • 全局变量在 WordPress 中很常见,但通常最好避免。当您在单个页面上多次使用相同的模板部分时,它们会起作用,但开始变得混乱。
  • 查询变量 ( get_query_var()/ set_query_var()) 不是为此目的而制作的。这是一种可能会引入意想不到的副作用的hacky 解决方法。