I created a child theme for the tweentysixteen theme template. I see the main loop located in index.php, but noticed that after the while statement, there is no display of wp_reset_postdata();
If I was to put it there, would the the loop gain any benefit?
For testing purposes I want to display a second loop under the first one, with page limits. I am assuming it should look like this…
$mposts = new WP_Query('posts_per_page=3');
while ( $mposts->have_posts() ) : $mposts->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
and if that is correct, do I place a wp_reset_query
, before this process or after it? if it is helpful to have it, why does it matter where it is placed?
Thanks!
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();
}