have_posts()

Whether current WordPress query has results to loop over.


Description Description


Return Return

(bool)


Top ↑

Source Source

File: wp-includes/query.php

function have_posts() {
	global $wp_query;
	return $wp_query->have_posts();
}

Top ↑

Changelog Changelog

Changelog
Version Description
1.5.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Codex

    Avoiding infinite loops:
    Calling this function within the loop will cause an infinite loop. For example, see the following code:

    while ( have_posts() ) : the_post();
        // Display post
        if ( have_posts() ) : // If this is the last post, the loop will start over
            // Do something if this isn't the last post
        endif;
    endwhile;
    

    If you want to check if there are more posts in the current loop without this unfortunate side effect, you can use this function:

    In your functions.php file:

    /**
     * Check if a loop has any more posts left.
     *
     * @global $wp_query
     *
     * @return bool True if there are any more posts in this loop, false if not.
     */
    function wpdocs_has_more_posts() {
      global $wp_query;
      return $wp_query->current_post + 1 < $wp_query->post_count;
    }
    

    In your template file:

    while ( have_posts() ) : the_post();
        // Display post
        if ( wpdocs_has_more_posts() ) :
            // Do something if this isn't the last post
        endif;
    endwhile;
    

You must log in before being able to contribute a note or feedback.