The have_posts() WordPress PHP function determines whether the current WordPress query has posts to loop over.
Usage
if (have_posts()) :
while (have_posts()) : the_post();
// Your loop code
endwhile;
else :
_e('Sorry, no posts were found.', 'textdomain');
endif;
Parameters
- None
More information
See WordPress Developer Resources: have_posts()
Examples
Basic usage of have_posts()
This example checks if there are any posts and loops through them if there are.
if (have_posts()) :
while (have_posts()) : the_post();
the_title(); // Display the post title
endwhile;
else :
_e('Sorry, no posts were found.', 'textdomain');
endif;
Avoiding infinite loops
This example demonstrates how to avoid infinite loops by using a custom function, wpdocs_has_more_posts(), to check if there are more posts in the current loop.
// In your functions.php file:
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();
the_title(); // Display the post title
if (wpdocs_has_more_posts()) :
// Do something if this isn't the last post
endif;
endwhile;
Displaying post title, featured image, and excerpt
This example displays the post title, featured image, and excerpt for each post.
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;
Custom WP_Query with have_posts() check
This example demonstrates how to use the have_posts() function with a custom WP_Query for a custom post type.
// 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;