Determines whether current WordPress query has posts to loop over.
Source
function have_posts() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
return false;
}
return $wp_query->have_posts();
}
Changelog
Version | Description |
---|---|
1.5.0 | Introduced. |
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
: