Resetting post data to previous loop in nested loops

I’m going to answer this myself, but it was the very clever @simonwheatley of Code for the People that solved this one for me.

Instead of using wp_reset_postdata() or wp_reset_query(), you can use the following:

$publication->reset_postdata();

Where $publication is your query object.

The working code now looks like:

$publication = new WP_Query( array(
'connected_type'  => 'publication_to_post',
'connected_items' => $post->ID,
'fields'          => 'ids',
'posts_per_page'  => 1,
) );

if ( $publication->have_posts() ) {
while ( $publication->have_posts() ) : $publication->the_post();
    echo '<h2>Publication title=".get_the_title()."</h2>';
    $pub_id = get_the_ID();

    $issue = new WP_Query( array(
        'connected_type'  => 'publication_to_issue',
        'connected_items' => $pub_id,
        'fields'          => 'ids',
        'posts_per_page'  => 1,
    ) );

    if ( $issue->have_posts() ) {
        while ( $issue->have_posts() ) : $issue->the_post();

            // need to be able to use template parts in here
            echo '<h2>Issue title=".get_the_title()."</h2>';

        endwhile; $publication->reset_postdata();
    }

    echo '<h2>Publication title=".get_the_title()."</h2>';

endwhile;
}

Leave a Comment