doune1000
doune1000
2018-09-07 20:12
浏览 35
已采纳

WordPress中具有相同WP_Query的多个循环

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?

<?php
$q = new WP_Query((array(
    'cat' => 1,
    'posts_per_page' => -1
)));

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

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

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

1条回答 默认 最新

  • dougehe2022
    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
        $this->rewind_posts();
    }
    

    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.

    点赞 评论

相关推荐