Breaking the loop?

WP loops are widely used to print lists of posts in WordPress:

<?php $loop = new WP_Query( array( 'post_type' => 'ff', 'ff' => 'show_ff', 'orderby' => 'menu_order', 'order' => 'ASC' ));
     while ( $loop->have_posts() ) : $loop->the_post(); ?> 

     <!-- here we're going to have all posts from show_ff category of ff type. -->

     <?php endwhile; ?>  

Is there a way of displaying for example 3 first posts then some element (div in my case) and again 3 next posts?

Read More

I know I could do 6 loops in each div, but maybe there’s another way of breaking this code? Maybe some if loops inside of while loop? Here’s my concept:

(...)
    while ( $loop->have_posts() ) : $loop->the_post(); 
     echo '3 first posts';
     echo '<div class="special"></div>';
     echo '3 last posts';
    endwhile; ?>  

Related posts

Leave a Reply

2 comments

  1. I don’t think i’ve fully grasped how you want this to work, but if i assume for a moment that as long as the loop has at least 6 posts, you want to insert extra markup after the third result in the loop..

    Example

    Insert extra markup after the third post, when the current iteration has at least 6 posts

    <?php
    if( $loop->have_posts() ) :
    
        //$post_count = $loop->found_posts; // <-- think this is the total, corrected below
        $post_count = $loop->post_count; // should be the result count for the current page
        $loop_count = 0;
    
        while ( $loop->have_posts() ) : $loop->the_post(); 
            $loop_count++;
            ?>
    
            <!-- your regular loop markup, eg. title, content, etc.. -->
    
            <?php
            if( $post_count >= 6 && $loop_count == 3 ) :
                ?>
    
                <!-- extra markup to put in when it's the end of the third post of this loop -->
    
                <?php
            endif;
        endwhile;
    endif;
    ?>
    

    This way you avoid the need to use an offset and can using paging if necessary. I havn’t tested the code, but i’ve given numerous examples like this before, simply let me know of any problems and i’ll re-examine(and test) the code.

  2. You can limit the number of posts to three in the first loop:

     <?php $args = array('showposts' => 3); 
    $the_query = new WP_Query($args); 
    while ($the_query->have_posts()) : $the_query->the_post();
    

    Then show your div and then show again 3 posts with the ‘offset’ parameter to exlude the 3 firsts ones:

     $args2 = array('showposts' => 3, 'offset' => 3 );
     $the_query = new WP_Query($args2); 
    while ($the_query->have_posts()) : $the_query->the_post(); 
    

    More infos in the codex.