Stickers
Stickers

Reputation: 78676

Multiple loops with same WP_Query in WordPress

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?
?>

Upvotes: 0

Views: 317

Answers (1)

Sean Bright
Sean Bright

Reputation: 120634

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.

Upvotes: 1

Related Questions