have_posts()

Whether current WordPress query has results to loop over.


Description Description


Return Return

(bool)


Top ↑

Source Source

File: wp-includes/query.php

863
864
865
866
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:

    1
    2
    3
    4
    5
    6
    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:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    /**
     * 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:

    1
    2
    3
    4
    5
    6
    while ( have_posts() ) : the_post();
        // Display post
        if ( wpdocs_has_more_posts() ) :
            // Do something if this isn't the last post
        endif;
    endwhile;
  2. Skip to note 2 content
    Contributed by Codex

    Default use:
    The following example can be used to determine if any posts exist and loop through them if they do.

    1
    2
    3
    4
    5
    6
    7
    if ( have_posts() ) :
        while ( have_posts() ) : the_post();
            // Your loop code
        endwhile;
    else :
        _e( 'Sorry, no posts were found.', 'textdomain' );
    endif;

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