Custom queries and wp_reset_postdata();

by Knownow   Last Updated October 19, 2019 13:08 PM - source

I am trying to understand how the loop works when you are using custom query and the use of wp_reset_postdata(); WP says

It is necessary to reset the main loop data after a nested loop so that some global variables hold the correct values again


What I understand of the loop (please correct me if I am wrong) is when its the default query ( eg. a request like /category/test ) WP creates a global $wp_query (an instance of WP_Query class) which has all the posts from the request . Inside the loop the_post() will set the global $post object to the current post from $wp_query each time the loop runs . We are thus able to use template tags like the_title() ( as template tags uses the global $post) when the loop runs .

In case of custom query like below :

$my_query->new WP_Query('category_name=xxxxx&posts_per_page=10') ;

Inside the loop for a custom query , $my_query->the_post will make global $post to have post from the object $my_query . wp_reset_postdata(); will reset the $post and make it have the post from $wp_query again .

So I have my category.php like below . This basically has the custom loop above inside the default loop so that I could test why to use wp_reset_postdata(); . For a request like category/test this will echo the title of each post with category of test along with all the titles of category ‘xxxxx’ each time .


          echo 'main title ';
          $my_query = new WP_Query('category_name=xxxxx&posts_per_page=10'); 
                echo '|';
 //echo nl2br("\n");
 // wp_reset_postdata();

The above code works even without using wp_reset_posdata() because (I am assuming ) after the inner loop is done the the_post() of the outer loop sets the global $post to contain the current post from the default query object ($wp_query) . Is my understanding correct ? If yes in what situation would you use wp_reset_postdata() .

I have been experimenting and reading a lot about the loop and custom queries and I am still unsure if I understand the concept correctly or not .

Tags : wp-query

Related Questions

Nested meta_query with multiple relation keys

Updated August 07, 2018 10:08 AM

Conditional posts in WP_query for search

Updated February 09, 2019 13:08 PM