如何使用 get_template_part 传递变量 [英] How to pass variable using get_template_part

查看:29
本文介绍了如何使用 get_template_part 传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 WordPress 网站上有三种类型的帖子(标准、旁白、视频).我需要在我的标准 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());$行++;终了;万一;?>

我的content.php文件代码:

<h2><a href="<?php the_permalink();?>>><?php the_title();?></a></h2><p><?php the_content();?>- <?php echo $row;?></p>

但是当我 echo $row; 什么都没有显示

我已经使用了这个链接来自一个关于stackoverflow的类似问题但是我无法更改我的帖子格式文件,还有其他方法吗?

解决方案

你不能精确地传递参数,但你可以做的是使用函数 set_query_varget_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");

(值得注意的是,它的最佳实践是最小化全局变量,因此您可能会更仔细地考虑重新构建模板结构,看看是否还有其他方法可以做到这一点,例如使用额外的模板部分.)

参考:

I have three types of posts on my WordPress site (standard, aside, video). I need to count a variable like $row in my standard content.php file But I am unable to pass it to content.php file.

My index.php file code:

<?php if (have_posts()) : 
           $$row = 2;
            while (have_posts()) : the_post();

            get_template_part('content', get_post_format());
            $row++;
            endwhile;
           endif; ?>

my content.php file code:

<div>
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <p><?php the_content(); ?>- <?php echo $row; ?></p>
</div>

but when I echo $row; nothing shows

I already use this link from a similar question on stackoverflow but I can't change my post format file, Is there another way to do this?

解决方案

You can't pass parameters exactly, but what you can do is use the functions set_query_var and get_query_var which makes the variables globally accessible.

In the main template, e.g. index.php, you use set_query_var to set the variable. Note that the first parameter is the name of the global variable, and this is what you use to retrieve it - not the original parameter name.

set_query_var( "my_global_var_name", $param_vaule); 
get_template_part('content', get_post_format());

Then in the template part, you can get the value of the now-global variable using get_query_var, e.g.

$myvar = set_query_var( "my_global_var_name" ); 

(It's worth noting that its best practice to minimise global variables, so you might be netter looking at restructuring your template structure to see if there is another way to do this, using extra template parts for example.)

References:

这篇关于如何使用 get_template_part 传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆