have_posts()
Whether current WordPress query has results to loop over.
Description Description
Return Return
(bool)
Source Source
File: wp-includes/query.php
863 864 865 866 | function have_posts() { global $wp_query ; return $wp_query ->have_posts(); } |
Expand full source code Collapse full source code View on Trac
Changelog Changelog
Version | Description |
---|---|
1.5.0 | Introduced. |
User Contributed Notes User Contributed Notes
You must log in before being able to contribute a note or feedback.
Avoiding infinite loops:
Calling this function within the loop will cause an infinite loop. For example, see the following code:
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:
In your
functions.php
file:/**
* Check if a loop has any more posts left.
*
* @global $wp_query
*
* @return bool True if there are any more posts in this loop, false if not.
*/
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();
// Display post
if
( wpdocs_has_more_posts() ) :
// Do something if this isn't the last post
endif
;
endwhile
;
Default use:
The following example can be used to determine if any posts exist and loop through them if they do.
if
( have_posts() ) :
while
( have_posts() ) : the_post();
// Your loop code
endwhile
;
else
:
_e(
'Sorry, no posts were found.'
,
'textdomain'
);
endif
;