【问题标题】:WordPress: passing $query to separate template fileWordPress:将 $query 传递给单独的模板文件
【发布时间】:2020-11-27 01:38:55
【问题描述】:

我有以下代码:

homepage.php

<?php
    $query = new WP_Query(
        array(
            'order'       => 'ASC',
            'orderby'     => 'menu_order',
            'post_type'   => 'work'
        )
    );
?>
<?php get_template_part('loop', 'feed-work'); ?>
<?php wp_reset_query(); ?>

loop-feed-work.php

<?php if($query->have_posts()) : ?>
    <?php while($query->have_posts()) : $query->the_post(); ?>
        <?php the_title(); ?>
    <?php endwhile; ?>
<?php endif; ?>

但是当我查看我的主页时,我收到以下错误:

致命错误:未捕获的错误:调用成员函数 have_posts() on ******/loop-feed-work.php:1 中的 null

这可能是因为查询位于不同的模板文件中吗?

【问题讨论】:

    标签: php wordpress wordpress-theming custom-wordpress-pages


    【解决方案1】:

    这正是问题所在。不幸的是 get_template_part 不像包含那样工作,因此在包含文件中时您将丢失范围变量。 在保持相同逻辑的同时解决该问题的方法是更改​​ get_template_part 并使用:

    // $templates[] = "{$slug}-{$name}.php"; // This is how wp builds the slug iside get_template_part
    include locate_template('loop-feed-work.php');
    

    【讨论】:

      猜你喜欢
      • 2019-05-15
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2016-09-15
      • 2017-11-09
      相关资源
      最近更新 更多