WordPress Loop For Even/Odd Posts

I have two columns and I want one post type to get distributed to each column evenly. So it’s two side-by-side divs and I want:

Div1 = Post1, Post3, Post5

Read More

Div2 = Post2, Post4, Post6

So basically get odd/even posts. Not exactly sure how to do it.

<?php query_posts('post_type=post-type'); ?>
<?php if (have_posts()) : ?>  
<?php while (have_posts()) : the_post(); ?>  

<div class="column1">
<?php 
  //Get Odd Posts
?>
</div>

<div class="column2">
<?php 
  //Get Even Posts
?>
</div>

 <?php endwhile; ?>  
<?php else : ?>  
//Something that happens when a post isn’t found.  
<?php endif; ?>  

Related posts

Leave a Reply

2 comments

  1. You want to use the modulus operator something like this:

    <?php
    $i = 0;
    
    for ($i = 0; $i <20; $i++){
        $class = $i % 2 == 0 ? "even" : "odd";
        echo "<div class='" . $class . "'>";
    
        echo "</div>";
    }
    ?>
    
  2. To do what you want, first you have to store the results somewhere (as even/odd), then display them.

    Though you should really target these posts with CSS, not PHP, as it’s hackish at best.

    <?php query_posts('post_type=post-type'); ?>
    <?php if (have_posts()) : ?>  
        <?php
            $i = 0;
    
            while (have_posts())
            {
                $key = $i & 1 ? 'odd' : 'even';
    
                $post[$key] = array(get_the_title() => get_the_content());
    
                $i++;
            }
        ?>
        <div class="column1">
            <?php foreach ($post['even'] as $title => $content) : ?>
                <?php echo $title; ?>
                <?php echo $content; ?>
            <?php endforeach; ?>
        </div>
        <div class="column2">
            <?php foreach ($post['odd'] as $title => $content) : ?>
                <?php echo $title; ?>
                <?php echo $content; ?>
            <?php endforeach; ?>
        </div>
    <?php else : ?>  
        //Something that happens when a post isn’t found.  
    <?php endif; ?>