WordPress:将 $query 传递给单独的模板文件

WordPress: passing $query to separate template file

我有以下代码:

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(); ?>

循环供稿-work.php

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

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

Fatal error: Uncaught Error: Call to a member function have_posts() on null in ******/loop-feed-work.php:1

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

这正是问题所在。不幸的是 get_template_part 不像 include 那样工作,因此在包含文件中时您将丢失 scope 变量。 在保持相同逻辑的同时解决该问题的方法是更改​​ 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');