WordPress.org

Support

Support » How-To and Troubleshooting » Problem with multiple loops

Problem with multiple loops

  • I use one loop to list posts from only 1 category in the sidebar, than I use another loop to show all the posts on index page.

    For some reason, after I started to used two loops, my “if” is not reacting to have_posts() anymore and jumps to “else” – which is 404 Page display. What can be wrong?

    It looks like:

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

    <– Code –>

    <?php endwhile; ?>
    <?php else : ?>

    <– 404 Page display –>

    <?php endif; ?>

Viewing 2 replies - 1 through 2 (of 2 total)
  • When you initialize a post loop with something like query_posts() it resets the posts object available on the page. So after the first loop is exhausted there are no further posts for the second loop to handle (because the original posts object is gone).

    To have two (or more) post loops in a template where one requires the default posts object, it’s better to create new query classes and work off these in your ‘secondary’ loops. Example:

    <?php
    $sidebar_posts = new WP_Query('cat=1&showposts=5');
    if ($sidebar_posts->have_posts()) : while ($sidebar_posts->have_posts()) : $sidebar_posts->the_post(); ?>

    And so on. The rest of the loop from here is no different than the standard one. Note that WP_Query() accepts the same arguments as query_posts().

    Thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Problem with multiple loops’ is closed to new replies.
Skip to toolbar