• Hey,

    I’ve been reading a book on theme development and I’m in the multiple loops section. So I thought I create myself an exercise, and so I created two loops in the index.php file as such:

    <?php
      $args = array("category_name" => "animation", "posts_per_page" => -1);
      $posts = get_posts($args);
    
      foreach ($posts as $post) : setup_postdata($post);
    ?>
    
    <h4><?php the_title(); ?></h4>
    <?php the_excerpt(); ?>
    
    <?php endforeach; wp_reset_postdata(); ?>

    So far so good. It works. There are 5 posts with the category “animation” and all the 5 will be displayed. So now, I wanted to add another loop. No real “purpose” here, as I said, it’s just learning, experimentation, etc with multiple loops, and I added this code after the one above.

    <?php if ( have_posts() ) : while (have_posts()) : the_post(); ?>
      <?php the_title(); ?>
    <?php endwhile; endif; ?>

    This second loop, however, outputs the 5 animation posts but I also get 5 additional error panels (WP_DEBUG is enabled). So I get a total of 10.

    Now, I’m thinking that by default WP outputs the first 10 posts. Since there are only 5 posts with the “animation” category, they get output correctly in the first loop, and they also get output in the second loop. But the second loop also gives me 5 error blocks – which totals 10 – which is what the default WP count is.

    I can’t seem to be able to figure out why this is. I’ve tried resetting the loop after the first one by using:
    – wp_reset_postdata()
    – wp_reset_query()
    – rewind_posts()

    and any of these combinations together, but doesn’t seem to result in any change. Not sure why I am getting the 5 errors after the 2nd loop. After all, if I understand correctly, the “get_posts()” method doesn’t alter the query. Any tips?

    Thank you.

    PS: I am using WP 4.4.2

  • The topic ‘Why this multi-loop doesn't work?’ is closed to new replies.