I’ve searched for this in the Q&A but I was unable to find it. When I read answers throughout the site I see wp_reset_postdata()
placed in multiple areas with the have_posts()
conditional and outside the conditional all together. When I read the documentation on wp_reset_postdata()
all it states is:
After looping through a separate query, this function restores the
$post global to the current post in the main query.
with a snippet of:
<?php
// example args
$args = array( 'posts_per_page' => 3 );
// the query
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- start of the secondary loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<!-- end of the secondary loop -->
<!-- put pagination functions here -->
<!-- reset the main query loop -->
<?php wp_reset_postdata(); ?>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
but when I reference other ways, such as “How to fix pagination for custom loops?” it’s after the conditional:
// Output custom query loop
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :
$custom_query->the_post();
// Loop output goes here
endwhile;
endif;
// Reset postdata
wp_reset_postdata();
Wouldn’t it be appropriate to have it afterwards and not within the have_posts()
conditional because if you do use an else statement the arguments aren’t being reset if you do not have posts. So my question is where should wp_reset_postdata()
go?