I have spent some time reading through the WordPress Codex, as well as various themes, and can see that some developers insert <?php wp_reset_postdata(); ?>
after the endif;
in a Blog Loop whilst others insert the code between the endwhile;
and endif;
of a Blog Loop. I have tried both locations but have yet to see a difference. Is there a correct location?
This function supposed to reset the secondery query that you run.. the function the_post
is letting you to use all the functions that you can run in the loop like the_title()
the_content
and so on..
So you reset the the_post
function and after the endwhile;
you can reset it already. and use your main query inside the if
statment too if you like.
<?php
// this is the main query check if there is posts
if ( have_posts() ) :
// loop the main query post and run the_post() function on each post that you can use the function the_title() and so on..
while ( have_posts() ) : the_post();
the_title(); // title of the main query
// the is second query
$args = array( 'posts_per_page' => 3 );
$the_query = new WP_Query( $args );
// check if there is a posts in the second query
if ( $the_query->have_posts() ) :
// run the_post on the second query now you can use the functions..
while ( $the_query->have_posts() ) : $the_query->the_post();
the_title();
the_excerpt();
endwhile;
// reset the second query
wp_reset_postdata();
/* here we can use the main query function already if we want..
its in case that you want to do something only if the second query have posts.
You can run here third query too and so on...
*/
the_title(); // title of the main query for example
endif;
endwhile;
endif;
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With