• I have a (relatively) tricky situation where my code requires changing the loop output every three posts, and within those three posts there are divs around two of the posts.

    The code below displays 6 posts and I would want to loop though a total of 24 posts, repeating this four times.

    Can anyone help? Thanks!

    FIRST THREE

    <div class="layer">
    
    <div class="large left">
        <div class="item">
        <?php the_title(); ?>
        <?php the_content(); ?>
        </div><!--item-->
    </div>
    
    <div class="small left">
        <div class="item">
        <?php the_title(); ?>
        <?php the_content(); ?>
        </div><!--item-->
    
        <div class="item">
        <?php the_title(); ?>
        <?php the_content(); ?>
        </div><!--item-->
    </div>
    
    </div><!--layer-->

    SECOND THREE

    <div class="layer">
    
    <div class="small left">
        <div class="item">
        <?php the_title(); ?>
        <?php the_content(); ?>
        </div><!--item-->
    
        <div class="item">
        <?php the_title(); ?>
        <?php the_content(); ?>
        </div><!--item-->
    </div>
    
    <div class="large right">
        <div class="item">
        <?php the_title(); ?>
        <?php the_content(); ?>
        </div><!--item-->
    </div>
    
    </div><!--layer-->

Viewing 2 replies - 1 through 2 (of 2 total)
  • assuing a ‘normal’ loop, i.e. no custom WP_query(), this code below should do what you are trying to achieve:

    while( have_posts() ) : the_post();
    
    $position = $wp_query->current_post;
    $p3 = $position%3;
    $p6 = $position%6;
    $number_posts = $wp_query->post_count-1;
    
    if( $p3 == 0 ) echo '<div class="layer">';
    if( $p6 == 0 ) echo '<div class="large left">';
    elseif( $p6 == 1 || $p6 == 3) echo '<div class="small left">';
    elseif( $p6 == 5 ) echo '<div class="large right">'; ?>
    
        <div class="item">
        <?php the_title(); ?>
        <?php the_content(); ?>
        </div><!--item-->
    
    <?php if( $position == $number_posts || in_array($p6, array(0, 2, 4, 5)) ) echo '</div>';
    if( $p3 == 2 || $position == $number_posts ) echo '</div><!--layer-->'; 
    
    endwhile;

    $wp_query->current_post is the current position of the post in the loop, starting with 0 zero for the first post.

    Thread Starter lechatlisse

    (@lechatlisse)

    That worked perfectly alchymyth, thank you so much!

    Pure genius!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Alternate loop output every three posts (within the same original loop)’ is closed to new replies.