wp-includes/class-wp-query.php:3727Check whether a WP_Query loop has posts left with have_posts(); true while posts remain, false at the end, when it also fires the loop_end action. Together with the_post() it drives the WordPress loop, for the main query via the global functions or directly on a custom WP_Query.
Determines whether there are more posts available in the loop.
boolEvery example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.
have_posts() advances nothing by itself; it reports whether the_post() has anything left to set up.
$recent = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 3,
) );
if ( $recent->have_posts() ) {
while ( $recent->have_posts() ) {
$recent->the_post();
echo '- ', get_the_title(), ' (', get_permalink(), ")\n";
}
wp_reset_postdata();
} else {
echo 'No posts matched.';
}
echo "\nposts returned: ", $recent->post_count, ' of ', $recent->found_posts, ' found';wp_reset_postdata() restores the global $post that the_post() overwrote.
2 hooks fire while WP_Query::have_posts() runs, in this order:
Fires if no results are found in a post query.
public function have_posts() { if ( $this->current_post + 1 < $this->post_count ) { return true; } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) { /** * Fires once the loop has ended. * * @since 2.0.0 * * @param WP_Query $query The WP_Query instance (passed by reference). */ do_action_ref_array( 'loop_end', array( &$this ) ); // Do some cleaning up after the loop. $this->rewind_posts(); } elseif ( 0 === $this->post_count ) { $this->before_loop = false; /** * Fires if no results are found in a post query. * * @since 4.9.0 * * @param WP_Query $query The WP_Query instance. */ do_action( 'loop_no_results', $this ); } $this->in_the_loop = false; return false; }Introduced in 1.5.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
src/wp-includes/class-wp-query.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.