2018-09-07 20:12
浏览 49


I have two loops with one same WP_Query, I tried place wp_reset_postdata(); either right after endwhile; in each loop, or just once after all loops (like below), both seems to be working.

What is the correct way of doing it, and why?

$q = new WP_Query((array(
    'cat' => 1,
    'posts_per_page' => -1

if ($q->have_posts()) :
    while ($q->have_posts()) : $q->the_post();
        // first loop

if ($q->have_posts()) :
    while ($q->have_posts()) : $q->the_post();
        // second loop

wp_reset_postdata(); // should reset be here or after endwhile; in each loop?
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dougehe2022 2018-09-07 22:19

    When WP_Query::have_posts() is called and it determines that there are no more posts, it automatically rewinds that query's result pointer to start over from the beginning. You can see the relevant code here, partially reproduced here:

    } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
        /* Some code removed here for the sake of brevity */
        // Do some cleaning up after the loop

    From the example code in the documentation, it seems that wp_reset_postdata() may only need to be called when you are dealing with multiple querys, but I don't know enough about WordPress to be definitive about that.

    解决 无用
    打赏 举报

相关推荐 更多相似问题