如何使用 get_template_part 传递变量
How to pass variable using get_template_part
我的 WordPress 网站上有三种类型的 post(标准、旁白、视频)。
我需要在我的标准 content.php
文件中计算像 $row
这样的变量,但我无法将它传递给 content.php
文件。
我的index.php
文件代码:
<?php if (have_posts()) :
$$row = 2;
while (have_posts()) : the_post();
get_template_part('content', get_post_format());
$row++;
endwhile;
endif; ?>
我的content.php
文件代码:
<div>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_content(); ?>- <?php echo $row; ?></p>
</div>
但是当我 echo $row;
什么都没有显示时
我已经在使用这个 link from a similar question on Whosebug 但我无法更改我的 post 格式文件,还有其他方法吗?
你不能准确地传递参数,但你可以做的是使用函数 set_query_var
和 get_query_var
这使得变量可以全局访问。
在主模板中,例如index.php,你用set_query_var
设置变量。请注意,第一个参数是全局变量的名称,这是您用来检索它的名称 - 而不是原始参数名称。
set_query_var( "my_global_var_name", $param_vaule);
get_template_part('content', get_post_format());
然后在模板部分,你可以使用get_query_var
获取now-global变量的值,例如
$myvar = set_query_var( "my_global_var_name" );
(值得注意的是,它的最佳实践是最小化全局变量,因此您可能会更好地查看重构模板结构,看看是否有另一种方法可以做到这一点,例如使用额外的模板部分。)
参考文献:
我的 WordPress 网站上有三种类型的 post(标准、旁白、视频)。
我需要在我的标准 content.php
文件中计算像 $row
这样的变量,但我无法将它传递给 content.php
文件。
我的index.php
文件代码:
<?php if (have_posts()) :
$$row = 2;
while (have_posts()) : the_post();
get_template_part('content', get_post_format());
$row++;
endwhile;
endif; ?>
我的content.php
文件代码:
<div>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_content(); ?>- <?php echo $row; ?></p>
</div>
但是当我 echo $row;
什么都没有显示时
我已经在使用这个 link from a similar question on Whosebug 但我无法更改我的 post 格式文件,还有其他方法吗?
你不能准确地传递参数,但你可以做的是使用函数 set_query_var
和 get_query_var
这使得变量可以全局访问。
在主模板中,例如index.php,你用set_query_var
设置变量。请注意,第一个参数是全局变量的名称,这是您用来检索它的名称 - 而不是原始参数名称。
set_query_var( "my_global_var_name", $param_vaule);
get_template_part('content', get_post_format());
然后在模板部分,你可以使用get_query_var
获取now-global变量的值,例如
$myvar = set_query_var( "my_global_var_name" );
(值得注意的是,它的最佳实践是最小化全局变量,因此您可能会更好地查看重构模板结构,看看是否有另一种方法可以做到这一点,例如使用额外的模板部分。)
参考文献: