Where should you reset postdata?

Short version:

As Tom J Nowell said,

You shouldn’t cleanup if there’s nothing to clean

Long version:

However, if you put wp_reset_postdata() after (or outside) the loop, it would still work perfectly fine. I have used the function in various scenarios, including something like this:

dynamic_sidebar( 'main-sidebar' );
wp_reset_postdata();

The reason was that some widget was querying posts without cleaning after itself.

Just keep in mind which query you want to reset. In Tom’s example, no matter if wp_reset_postdata is within the if statement or not, once it gets called, you will have problems because it will directly go back to the main post instead of the parent custom loop.

What the function does is tell a WP_Query object to restore the current post to the global scope. Since it’s a function instead of a method, then there is a single object it works with – the global $wp_query instance of the WP_Query object.

If you have custom loops, where you use a newly generated WP_Query, you should use the reset_postdata method of that query:

$pages = new WP_Query( 'post_type=page' );
while( $pages->have_posts() ) {
    $pages->the_post();

    // Page title
    echo '<h1>'; the_title();  echo '</h1>';

    $books = new WP_Query( 'post_type=book&...' );
    if( $books->have_posts() ) {
        while( $books->have_posts() ) {
            $books->the_post();

            // Book title
            echo '<li>'; the_title(); echo '</li>';
        }

        // Don't go back to the global post, go back to the "page"
        // wp_reset_postdata();
        $pages->reset_postdata();
    }

    // Page content
    the_content();
}

// Finally, reset the main query
wp_reset_postdata();

Hope this sums it up 🙂

Leave a Comment