WordPress.org

Forums

Problem with multiple loops (3 posts)

  1. Brody
    Member
    Posted 9 years ago #

    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; ?>

  2. Kafkaesqui

    Posted 9 years ago #

    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().

  3. Brody
    Member
    Posted 9 years ago #

    Thanks!

Topic Closed

This topic has been closed to new replies.

About this Topic