Alternate post_class on each post

I need to have an alternating (even, odd…) class on posts to provide alternate highlights on a column. The best thing would be to attach this to the post_class() so that it’s on every instance of post_class(). Below is the code I have at this point to achieve this effect.

<?php 

// setting other variables for alternating categories
$style_classes = array('even', 'odd');
$style_counter = 0;
?>

<?php if (have_posts()) : ?>

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

<div class="<?php $k = $style_counter%2; echo $style_classes[$k]; $style_counter++; ?>">

<?php the_cotent(); ?>

</div>

<?php endwhile; ?>

<?php endif; ?>

4 Answers
4

You should add the following code in functions.php:

add_filter ( 'post_class' , 'my_post_class' );
global $current_class;
$current_class="odd";

function my_post_class ( $classes ) { 
   global $current_class;
   $classes[] = $current_class;

   $current_class = ($current_class == 'odd') ? 'even' : 'odd';

   return $classes;
}

This ensures that all the odd posts on the page will have the class ‘odd’ and all the even posts will have the class ‘even’ just by using post_class() in your theme.

Leave a Comment