Adding Odd and Even Class to Posts on WordPress


<?php if (have_posts()) : while (have_posts()) : the_post();?>
   <div class='<?php echo (++$j % 2 == 0) ? 'odd' : 'even'; ?>'>
      <p><?php the_title(); ?></p>
   </div>
<?php endwhile; endif; ?>

Let’s see the results when you apply the above codes, let’s say you have 4 published posts, and you used the html structure below


<div class="odd" >
      <p>Post One</p>
</div>

<div class="even" >
      <p>Post Two</p>
</div>

<div class="odd" >
      <p>Post Three</p>
</div>

<div class="even" >
      <p>Post Four</p>
</div>

Since each divs has now unique classes, we can now manipulate the style for each post using CSS.

ex.


<style>
.even,.odd {
   padding: 20px;
   border: 1px solid #cccccc; 
   margin-bottom: 10px;
}
.even {
   background: #ffffff;
}
.odd {
   background: #cccccc;
   color: #ffffff;
}
</style>

Here’s the result

Post One

Post Two

Post Three

Post Four