wp_reset_postdata() or wp_reset_query() after a custom loop?

Reading some stuff about query_reset_postdata and query_reset_query makes me confused. For example:

  1. Is there any need to use both wp_reset_postdata and wp_reset_query together?

  2. http://www.poststat.us/properly-reset-wordpress-query/

Above states that you should only use query_reset_postdata() when using “separate queries”.
In example2 there’s a comment:

WP_Query( $args ) = wp_reset_postdata();

AND

query_posts ( $args ) = wp_reset_query();

And really you should never use wp_reset_query because you shouldn’t use query_posts!?

In the WP Codex it states that you should use wp_reset_query() after a custom loop (first example) http://codex.wordpress.org/Function_Reference/wp_reset_query

Is the codex wrong then?

1

The difference between the two is that

  • wp_reset_query() – ensure that the main query has been reset to the original main query
  • wp_reset_postdata() – ensures that the global $post has been restored to the current post in the main query.

Indeed, looking at the source you’ll see that the wp_reset_query() calls wp_reset_postdata(). The only difference between the two then is this line:

$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];

(in wp_reset_query()). So wp_reset_query() is only necessary should those two globals differ, and that only happens if query_posts() has been used somewhere.

When should I use them?

Simply put:

  • wp_reset_postdata() – immediately after every custom WP_Query()
  • wp_reset_query() – immediately after every loop using query_posts()

Should I use wp_reset_query

Well, yes, but it’s only needed after using query_posts(). As you’ve pointed out you should never use query_posts(). So if you aren’t ever using query_posts() then it’s not necessary to call wp_reset_query() (instead of wp_reset_postdata().

In short, it’s not that you shouldn’t use wp_reset_query() instead of wp_reset_postdata(), it’s that you shouldn’t ever need to!

Leave a Comment