have_posts(): bool

Determines whether current WordPress query has posts to loop over.

Return

bool True if posts are available, false if end of the loop.

More Information

This function checks whether there are more posts available in the main WP_Query object to loop over. It calls have_posts() method on the global $wp_query object.

If there are no more posts in the loop, it will trigger the loop_end action and then call call rewind_posts() method.

Source

function have_posts() {
	global $wp_query;

	if ( ! isset( $wp_query ) ) {
		return false;
	}

	return $wp_query->have_posts();
}

Changelog

VersionDescription
1.5.0Introduced.

User Contributed Notes

  1. Skip to note 6 content

    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;
  2. Skip to note 7 content
    <?php if ( have_posts() ) : while( have_posts()  ) : the_post(); ?>
        <h1><?php the_title(); ?></h1>
        <a href="<?php the_permalink(); ?>">
            <?php the_post_thumbnail( 'full' ); ?>
        </a>
        <p><?php the_excerpt(); ?></p>
    <?php endwhile; endif; ?>

    Output:
    Post title
    Post featured full size image (When anyone click on the image then open post single page)
    Post small description

    Edited by @audrasjb: Small WPCS fixes.

  3. Skip to note 8 content

    Example: if creating a custom WP_Query out of the standard WP loop context. This example uses have_posts() function extended from WP_Query:

    <?php
    // Define args
    $args = array('post_type' => 'custom_post_type');
    
    // Execute query
    $cpt_query = new WP_Query($args);
    
    // Create cpt loop, with a have_posts() check!
    if ($cpt_query->have_posts()) :
      while ($cpt_query->have_posts()) : $cpt_query->the_post(); ?>
    
        <?php the_title(); ?>
    
    <?php endwhile;
    endif; ?>

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