WordPress.org

Ready to get started?Download WordPress

Codex

Function Reference/have posts

Contents

Description

This function checks to see if the current WordPress query has any results to loop over. This is a boolean function, meaning it returns either TRUE or FALSE.

As a side effect, have_posts starts, steps through, or resets The Loop. At the end of the loop, have_posts returns 0 after calling rewind_posts.

Usage

<?php have_posts(); ?>

Parameters

This function does not accept any parameters.

Return Values

(boolean) 
True on success, false on failure.

Examples

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

<?php
if ( have_posts() ) :
	while ( have_posts() ) : the_post();
		// Your loop code
	endwhile;
else :
	echo wpautop( 'Sorry, no posts were found' );
endif;
?>

Note

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

<?php
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.

function more_posts() {
  global $wp_query;
  return $wp_query->current_post + 1 < $wp_query->post_count;
}

Change Log

Source File

have_posts() is located in wp-includes/query.php.

Related

Articles

Code Documentation

  • Class: WP_Query - Detailed Overview of class WP_Query
  • Object: $wpdb - Overview on the use of the $wpdb object
  • Function: get_query_var()
  • Function: query_posts() - Create additional custom query
  • Function: get_post() - Take an ID of an item and return the records in the database for that article
  • Function: get_posts() - A specialized function that returns an array of items
  • Function: get_pages() - A specialized function that returns an array of pages
  • Function: have posts() - a condition that determines whether the query returned an article
  • Function: the_post() - Used to automatically set the loop after a query
  • Function: rewind_posts() - Clears the current loop
  • Function: setup_postdata() - Sets the data for a single query result within a loop
  • Function: wp_reset_postdata() - Restores the previous query (usually after a loop within another loop)
  • Function: wp_reset_query()
  • Function: is_main_query() - Ensures that the query that is being changed is only the main query
  • Action Hook: pre_get_posts - Change WordPress queries before they are executed
  • Action Hook: the_post - Modify the post object after query
  • Filter Hook: found_posts - Changes the value of the object found_posts WP_Query
See also index of Function Reference and index of Template Tags.