0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.