Support » Themes and Templates » Nested Loop problem

  • Hey everyone,

    I’m trying to do a nested loop in WordPress. I can get the start of the outer loop, and the content of the inner loop to display fine. But I can’t get it to snap back to the original loop afterwards. It just proceeds as though it’s still in the inner loop.

    Important bits

    $associatedPosts = $newsletter->get_related_posts();
    //Start the sub-loop & save the original.
    $temp_query = clone $wp_query;
    $sub_loop_1 = new WP_Query(array('post__in' => $associatedPosts));
    while ($sub_loop_1->have_posts()) : $sub_loop_1->the_post();
    ?>
    <h3><?php the_title(); ?></h3>
    <div class="entry-content">
    <?php
    if(has_post_thumbnail()) {
    	the_post_thumbnail();
    }
    ?>
    <?php the_excerpt(); ?>
    </div>
    <hr style="border: 1px solid black;" />
    <?php
    endwhile;
    $wp_query = clone $temp_query;
    ?>

    I tried cloning the wp_query object, but that doesn’t have any effect. For instance, the last post in this inner loop is the “hello world” post. So at the bottom of the page, the comments for “hello world” are shown, instead of the comments for the post in the outer loop.

    Any help would be much appreciated. Thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Sounds as though your main loop is getting over written by your new loop instance. See the “Important Note” on this page.

    Would it be possible that you could just iterate through the array with a foreach? — something like…


    $associatedPosts = $newsletter->get_related_posts();
    foreach($associatedPosts as $post) : setup_postdata($post); ?>
    <!-- Put you HTML output here using template_tags where necessary -->
    <?php endforeach; ?>

    … then again I’m not sure how get_related_posts() works as i’ve not used it myself. Is it a plugin?

    hth

    Thread Starter vital101

    (@vital101)

    Thanks! Somehow I skipped right over that “Important Note”. The get_related_posts function is from a plugin I’m writing, and returns the post ID’s of some some related posts.

    I ended up with

    $associatedPosts = $newsletter->get_related_posts();
    //Start the sub-loop & save the original.
    foreach($associatedPosts as $aPost){
         $tmpPost = get_post($aPost);
         setup_postdata($tmpPost);

    After that, the template tags worked fine and it didn’t clobber the main Loop.

    Also, as a note, don’t use the variable “post”. It screws with the WordPress global “post”.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Nested Loop problem’ is closed to new replies.