I’ve tested some piece of simple code, but the result is so so strange.
Test 1:
$featured_posts = new WP_Query( $query_args );
while ($featured_posts->have_posts()) {
$featured_posts->the_post();
the_title(); echo '<br>';
}
echo 'End: "' . $featured_posts->have_posts() . '"'; // have_post() is TRUE, WHY?
Test 2:
$featured_posts = new WP_Query( $query_args );
$have_posts = $featured_posts->have_posts();
while ($have_posts) {
$featured_posts->the_post();
the_title(); echo '<br>';
$have_posts = $featured_posts->have_posts();
}
echo 'End: "' . $have_posts . '"'; // false -> I think false is right.
echo 'End: "' . $featured_posts->have_posts() . '"'; // but still TRUE, WHY?
Am I missing anything?
If we look at
have_posts()
in source, we can see why this happens:When it reaches the end of the loop, it calls
rewind_posts
, which resetscurrent_post
back to-1
, so the next call tohave_posts
will return true again.