Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I place wp_reset_postdata(); after endwhile; or endif; ?

Tags:

php

wordpress

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?

like image 585
Craig Avatar asked Sep 01 '25 01:09

Craig


1 Answers

This function supposed to reset the secondery query that you run.. the function the_postis 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;
?>
like image 194
Shibi Avatar answered Sep 02 '25 17:09

Shibi