What is difference between WordPress functions rewind_posts()
, wp_reset_postdata()
and wp_reset_query()
and when I should use them?
If I have this part of code in single.php
:
$query = new WP_Query($some_args);
while ($query->have_posts()) : $query->the_post();
...
endwhile;
is this equal to this:
$query = new WP_Query($some_args);
while (have_posts()) : the_post();
...
endwhile;
The two statements in your question aren’t equal.
In the first block you’re looping through posts returned by your custom WP_Query,
$query
.In the second block
$query
doesn’t do anything and the posts are actually from the global$wp_query
.Let’s look at what each of the three functions you mentioned do.
rewind_posts()
– This does exactly what it sounds like. After you’ve run a loop this function is used to return to the beginning allowing you to run the same loop again.wp_reset_postdata()
– In your first block of code you run a custom WP_Query. This will modify the global$post
variable. After that query has been run usingwp_reset_postdata()
will restore the global$post
variable back to the first post in the main query.wp_reset_query()
– This should be used if you change the global$wp_query
or usequery_posts()
(I wouldn’t suggest usingquery_posts()
). It resets$wp_query
back to the original.Further reading:
http://codex.wordpress.org/Function_Reference/rewind_posts
http://codex.wordpress.org/Function_Reference/wp_reset_postdata
http://codex.wordpress.org/Function_Reference/wp_reset_query
Rewind post – Rewinds to the beginning of the cycle.It generally the clears the current loop. Example
You probably donât need wp_reset_query(). wp_reset_query() unsets the main $wp_query variable, then resets it to the value of $wp_the_query, and then runs wp_reset_postdata(). Well, if youâre not using query_posts(), then you really shouldnât be messing with the main $wp_query variable, as wp_reset_query() does.
All you need to do after a custom WP_Query is use wp_reset_postdata(), which resets various global post variables to their original values.
Reference here