WordPress.org

Ready to get started?Download WordPress

Forums

Alternate loop output every three posts (within the same original loop) (3 posts)

  1. lechatlisse
    Member
    Posted 2 years ago #

    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-->
  2. 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.

  3. lechatlisse
    Member
    Posted 2 years ago #

    That worked perfectly alchymyth, thank you so much!

    Pure genius!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags