Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress: Difference between rewind_posts(), wp_reset_postdata() and wp_reset_query()

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;
like image 979
Michal Avatar asked May 19 '14 04:05

Michal


1 Answers

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 using wp_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 use query_posts() (I wouldn't suggest using query_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

like image 181
Nathan Dawson Avatar answered Sep 30 '22 18:09

Nathan Dawson