0

I'm confused about an example from the docs:

<?php
    // The main query.
    if ( have_posts() ) : while ( have_posts() ) : the_post();
        the_title();                                                             
        the_content();                                                          
    endwhile;                                                                   
    else :                                                                      
        // When no posts are found, output this text.                           
        _e( 'Sorry, no posts matched your criteria.' );                         
    endif;                                                                       
    wp_reset_postdata();                                                        

    /*                                                                          
     * The secondary query. Note that you can use any category name here. In our example,
     * we use "example-category".                                               
     */                                                                        
    $secondary_query = new WP_Query( 'category_name=example-category' );        

    // The second loop. if ( $secondary_query->have_posts() ) 
    echo '<ul>';
    while ( $secondary_query->have_posts() ) :
        $secondary_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    endwhile;
    echo '</ul>';
    endif;
wp_reset_postdata();
?>

Isn't the first wp_reset_postdata() completely redundant? Before querying $post, the secondary query overwrites it anyways right? Is there ever a case where it makes sense to call wp_reset_postdata() after the main loop?

1 Answer 1

3

The first use of wp_reset_postdata() is not redundant its unnecessary.

Per the codex

Use this function to restore the global $post variable of the main query loop after a secondary query loop using new WP_Query. It restores the $post variable to the current post in the main query.

So only use it after your secondary query to reset things back for your main query.

NOTE: a better location to put it would be within the if instead of after the else

if ( $arg ) :
    // loop
    wp_reset_postdata();
else :
    // no results
endif;

More infor on wp_reset_postdata()

2
  • Thanks for the answer. One small thing: AFAIK "redundant" and "unnecessary" can be used synonymously here. That is why - to me - your first sentence makes no sense.
    – ben
    Commented Jul 25, 2016 at 16:44
  • @ben technically the first time you use something its not redundant, but it can be unnecessary
    – stoi2m1
    Commented Jul 25, 2016 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.