4

I have been pretty impressed with the recent redesign at WebDesignerDepot and I am curious about the mechanics of their homepage. I like how they have featured post sections that break up the monotony of the page, but I haven't figured out how to incorporate something similar in my own designs. I'm guessing that they are using multiple loops and it seems like it's something like [main loop chronological] --- > [custom loop] ---> [main loop continues chronologically].

How would I break off into a custom loop and then continue where I left off in the main loop?

1 Answer 1

8

You can use current_post within the loop to track where you are and split the loop into multiple parts:

while ( have_posts() ) :
    the_post();

    // only output content if it's post 1 - 5
    if( 5 > $wp_query->current_post ):
        the_title();
    else :
        break;
    endif;

endwhile;

// do another query/loop
$custom_loop = new WP_Query( $args );
while( $custom_loop->have_posts() ) :
    // etc..
// snip....


// output posts 6 + of main query
while ( have_posts() ) :
    the_post();

    the_title();

endwhile;

You can also use $wp_query->rewind_posts(); to run the same loop again, or set current_post directly to start a loop at a specific post:

// start a loop at post 6
$wp_query->current_post = 5
while ( have_posts() ) :
    the_post();
    // etc..

Just remember that current_post is zero-indexed, it starts at zero, not 1.

2
  • Could you explain how this does not waste database resources. Is it because there are no wp_reset_postdata(); being called?
    – tmyie
    Commented Mar 2, 2014 at 17:45
  • @tmyie - I'm not sure I understand your question. the loop iterates over a query object, it doesn't itself do the querying. you can run through the same loop multiple times from a single initial query.
    – Milo
    Commented Mar 2, 2014 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.