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:

Read More
$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;

Related posts

Leave a Reply

2 comments

  1. 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

  2. Rewind post – Rewinds to the beginning of the cycle.It generally the clears the current loop. Example

    <? Php  
    / / use the cycle for the first time 
    if ( have_posts ( )  ) {  while ( have_posts ( ) ) { the_post ( ) ;  ?> 
        < ! - - display information about the post - - > 
    <? php  }  }  ?>
    
    
        < ! - - any - anything any code - - >
    
    
    <? Php  
    / / use the cycle for the second time 
    / / rewind to the beginning of the cycle to once again ispolzvoat heve_posts () 
    rewind_posts ( ) ; 
    if ( have_posts ( )  ) {  while ( have_posts ( ) ) { the_post ( ) ;  ?> 
        < ! - - display information about the post - - > 
    <? php  }  }  ?>
    

    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