【问题标题】:How to pass variable using get_template_part如何使用 get_template_part 传递变量
【发布时间】:2020-07-02 17:16:40
【问题描述】:

我的 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());
            $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; 什么都没有显示

我已经使用此链接from a similar question on stackoverflow,但我无法更改我的帖子格式文件,还有其他方法吗?

【问题讨论】:

    标签: php wordpress wordpress-theming


    【解决方案1】:

    您无法准确传递参数,但您可以使用函数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获取现在全局变量的值,例如

    $myvar = set_query_var( "my_global_var_name" ); 
    

    (值得注意的是,最小化全局变量的最佳做法是,因此您可能会更加关注重构模板结构,看看是否有其他方法可以做到这一点,例如使用额外的模板部分。)

    参考资料:

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-20
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多