When to use wp_reset_postdata();

First we should talk about why you need to use wp_reset_query() in the first place.

What wp_reset_query() does is reset the global $wp_query object back to it’s original state. Since you’re creating a new WP_Query object / instance, it does not overwrite the global $wp_query object. The only real case you would need to call this function is if you’re using query_posts() which you shouldn’t be in 99% of cases.

Whenever you loop through a custom WP_Query ( using The Loop as you have above ) it will overwrite the global $post object which means we should be using wp_reset_postdata() instead. Since it only happens during The Loop process, we should call the function after The Loop. We should be checking to ensure we have posts in the first place and to ensure we don’t call this function unnecessarily we would want to put it inside the conditional as seen in the example below:

$myquery = new WP_Query( $args );

if( $myquery->have_posts() ) {

    while( $myquery->have_posts() ) {
        $myquery->the_post();
        /** Content **/
    }

    wp_reset_postdata();
}

Leave a Comment