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
File: wp-includes/query.php
.
View all references
function have_posts() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
return false;
}
return $wp_query->have_posts();
}
Changelog
Version | Description |
---|---|
1.5.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
Default use:
The following example can be used to determine if any posts exist and loop through them if they do.
Avoiding infinite loops:
Calling this function within the loop will cause an infinite loop. For example, see the following code:
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:In your template file:
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.
Example: if creating a custom WP_Query out of the standard WP loop context. This example uses
have_posts()
function extended fromWP_Query
: