Sometimes It’s inadequate to build multiple loops in WordPress because WordPress keeps the track of loop or query data and in my WordPress application, I want different kinds of values/post in global variable post so its display different post from different category, from custom post type and etc within a single page.so for that I must have to reset the previous query.
To destroy the previous query used in a custom loop, we need to reset WordPress loop.So to reset loop explicitly, we can use WordPress inbuilt functions.
Let’s have a look into WordPress in-built functions which are used to reset loop
How to use wp_reset_postdata() function?
wp_reset_postdata() is a wordpress inbuilt function which used to reset the global $post variable to the current post in the query.This function is included in file /wp-includes/query.php.Its has no parameter and return nothing.wp_reset_postdata() restores the value of the global variable $post used in the current page.
Example of wp_reset_postdata() after a WP_Query
$post = new WP_query(); $post->query('cat=3&showposts=1&orderby=rand'); while ($post->have_posts()) : $post->the_post(); endwhile; wp_reset_postdata();
As far as you can see, wp_reset_postdata() method is very simple in application. It takes no parameters and returns no values. It simply resets the data recording after an arbitrary query. You can use wp_reset_postdata, to return a query object in its initial state. Sometimes you write code after while loop and it lead to unexpected results, at that time wp_reset_postdata() is useful.
How to use wp_reset_query()?
Next is the wp_reset_query function and it resets previous the query used with custom loops. wp_reset_query is a simple function has no parameter and return nothing.wp_reset_query() function resets the global variable $post and $wp_query used in the current page. This function also have no parameters and returns no value.
query_posts( 'posts_per_page=3' ); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
Above function should be used after query_posts() and before another query_posts().This function resets the previous wp_query object.wp_reset_query() method also eliminates the previous request before continue to next task.
NOTE: wp_reset_query() function resets the both global variables $wp_query and $post whereas wp_reset_postdata() only resets the $post variable.
Thus, the wp_reset_query() function is best used after query_posts loop to relieve a variety of data after the arbitrary query.
You may also like: To Exclude Latest Post from the WordPress Loop
If you have any questions about wp_reset_query() or wp_reset_postdata() function, leave a comment and we'll get back to you.