WordPress Have_Posts: How to Use WordPress Have_Posts

WordPress Have_Posts is a function available in WordPress core. This WordPress Have_Posts function is used to check in a loop if there are posts for the loop over. This function returns the value of True or False. If there will be posts available for looping over, WordPress Have_Posts will return True and if there will be no post to loop over, WordPress Have_Posts will return False. 

It will automatically call Rewind_Posts when the loop has finished. 

WordPress Have_Posts Usage:

Here is how you can use this function in PHP:

 

 

php rewind_posts(); ?>

You can see that it is used much like any other wordpress function or PHP function. 

How to Use WordPress Have_Posts:

In the below example you can see a loop code in which this function is used:

php
if ( have_posts() ) :
	while ( have_posts() ) : the_post();
		// The post will be displayed when the loop runs
	endwhile;
else :
	echo wpautop( 'Sorry, no posts were found' );
endif;
?>

 wordpress Have_postsHowever, you should be careful that if you use WordPress Have_Posts within a loop itself, it will go into an infinite loop. This is one of the mistakes programmers make that they yse WordPress Have_Posts whing a loop. In the below example you can see the error code which will lead to infinite loop:

php
while ( have_posts() ): the_post();
        // Display post
        if ( have_posts() ): // The loop will go on even when it reaches the last post because it will restart. 
        endif;
endwhile;
?>

This will lead to infinite loop. You can use the wordpress function More_Posts if you want to check if there are more posts in the current loop. But as i said, using WordPress Have_Posts inside a loop will result in a never ending loop. 

I hope this small little tutorial on WordPress Have_posts function will have clarified your concepts about it and you will be able to use it more precisely without falling into unending loop cycle. 

 

Leave a Reply