Ads by ProfitSence

WordPress have_posts Example

Last Updated on Wednesday 5th Oct 2022


Determines whether current WordPress query has posts to loop over.


  • (bool) True if posts are available, false if end of the loop.
  • 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 rewind_posts() method.

WordPress have_posts

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

  • Use the if part if you want to have something different show up when there are no posts.
  • This is particularly useful, example like category archive page.

WordPress have_post

					if ( have_posts() ):
  // Yep, we have posts, so let's loop through them.
  while ( have_posts() ) : the_post();
  // do your loop
else :
  // No, we don't have any posts, so maybe we display a nice message
  echo "<p class='no-posts'>" . __( "Sorry, there are no posts at this time." ) . "</p>";