Outputting odd or even posts in PHP with different parent wrappers — WordPress

Here’s what I am trying to accomplish:

I want to output different posts depending on whether they are odd or even with different parent wrappers for the odd posts and the even posts. For example, the even posts may be outputted to a parent with a class of evenWrapper and the odd posts may be outputted to a parent with a class of oddWrapper.

Read More

I get the overall theory behind using the modulus operator. Where I am getting stuck is actually wrapping the even or odd posts in different parent wrappers. Here is what I have so far:

<?php if ( have_posts() ):
$c = 0;
?>


<div class="six columns alpha">

<?php 
while ( have_posts() ) : the_post();

    if($c % 2 == 0) : ?>

        <?php /* posts with even numbers are outputted here */ ?>

<?php   
    endif;
$c++;
endwhile;

?>

</div>

<?php endif; ?>

The above code works fine for outputting even posts. As you can see, the parent wrapper is around the while loop and checks with an if statement using the modulus operator. My first guess would be to create an else statement and wrap a different parent around them if they aren’t even. But I run into the problem of it being caught in the while loop and outputting the parent wrapper each time.

How would I proceed from here to output even posts into another parent container?? Do I have to make another while loop?

Related posts

Leave a Reply

3 comments

  1. I’m not fully up to speed on the WordPress API so there may or may not be a better way to get post details, but this should work regardless:

    <?php
        $oddPosts = array();
        $evenPosts = array();
        $i = 0;
    ?>
    <?while(have_posts()) : the_post()?>
    <?
        $post = the_content(); // etc...
        if(++$i % 2 == 0) {
            array_push($evenPosts, $post);
        } else {
            array_push($oddPosts, $post);
        }
    ?>
    <?endwhile;?>
    
    <div class="wrapper odd">
        <?foreach($oddPosts as $post):?>
            <?= $post ?>
        <?endforeach?>
    </div>
    <div class="wrapper even">
        <?foreach($evenPosts as $post):?>
            <?= $post ?>
        <?endforeach?>
    </div>
    
  2. It’s really simple, actually. And yes, you need an else statement too. Here’s an example:

    <?php if ($c % 2 === 0): ?>
    <div class="evenWrapper">
    <?php else: ?>
    <div class="oddWrapper">
    <?php endif; ?>
    ...
    </div>
    

    You can also do something like this:

    <?php
    $class = $c % 2 === 0 ? 'evenWrapper' : 'oddWrapper';
    ?>
    <div class="<?php echo $class; ?>">
    </div>
    
  3. just use $wp_query->current_post to get the current index position of the post:

    <?php if (($wp_query->current_post) % 2) $class="evenWrapper"; else $class="oddWrapper"; ?>
    
    <article <?php post_class($class); ?>>
     ...content here ...
    </article>