WordPress at a glance

have_posts() WP 1.5.0

Checks if the current WP query has results for output, i.e. if there are posts available for output on the current page. Conditional tag.

At the end of the WordPress Loop, the Function automatically returns a mark that the request is complete and ready for output again, i.e. the function rewind_posts() triggered automatically.

Notes:

  • Global. WP_Query. $wp_query Global WP_Query instance.
✈ 1 time = 0.000001s = speed of light | 50000 times = 0.02s = speed of light PHP 7.2.5, WP 4.9.6

No Hooks.

Return

true/false.

  • false if there are no results to output.
  • true if there is something to output.

Usage

<?php
if( have_posts() ){
	// ...
}
?>

Examples

#1 Determine whether there are records for output

The following example can be used to determine if there are posts to output and if there are, then run while part of the loop and output them:

<?php
if( have_posts() ){
	while( have_posts() ){
		the_post();
		// output code
	}
}
else {
	echo wpautop( 'No posts found for output.' );
}
?>

#2 Calling have_posts() inside a WordPress Loop

Calling have_posts () inside a WordPress Loop means an infinite loop. See the example:

while( have_posts() ){
	the_post();

	// Post output
	if( have_posts() ){ // If this is the last post, the cycle will start again
			// Do something, if this is not the latest post
	}
}

2.1. If you want to check if there are more posts in the current loop, you can use the following function.

This function will return true if there are posts in the query and false if the last post was outputted.

more_posts() must be used instead of have_posts() from above (example 2).

function more_posts() {
	global $wp_query;
	return $wp_query->current_post + 1 < $wp_query->post_count;
}

Code of have_posts: wp-includes/query.php VER 4.9.8

<?php
function have_posts() {
	global $wp_query;
	return $wp_query->have_posts();
}

Related Functions

From tag: query

More from tag: Conditional tags (all)

More from category: Queries

More from Template Tags: Posts, Pages, ...

No comments
    Hello, !     Log In . Register