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; ?>
link|improve this question

feedback

2 Answers

up vote 5 down vote accepted

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.

link|improve this answer
feedback

This works, it passes in the additional class into post_class():

<?php $c = 0; ?>
<?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
        <div <?php post_class((++$c % 2 === 0) ? 'odd' : 'even'); ?>>
            <?php the_content(); ?>
        </div>
    <?php endwhile; ?>
<?php endif; ?>

EDIT: Here's a way that creates a version of post_class() that will keep track of the count on the page. Now, it will use a new name, oddeven_post_class() but it does work as you want. All you need to do is drop this into functions.php:

/* Drop this block into functions.php */
class MyCounter {
    var $c = 0;
    function increment(){
        ++$this->c;
        return;
    }
    function oddOrEven(){
        $out = ($this->c % 2 === 0) ? 'odd' : 'even';
        $this->increment();
        return $out;
    }
}
$my_instance = new MyCounter();
function post_class_oddeven() {
    global $my_instance;
    ob_start();
    post_class($my_instance->oddOrEven());
    $str = ob_get_contents();
    ob_end_clean();
    echo $str;
}
/* end block */

So to call it, use post_class_oddeven() in your theme wherever you would call post_class()

link|improve this answer
Yeah that's still just a variation on the solution above. I may not have been clear but I'm looking for a solution that would go in the functions.php file and then just passes it to any isntance of post_class(). Then I don't have to modify all the individual instances of loops where I need this. – curtismchale Aug 12 '10 at 4:21
Updated my answer with a solution that works for me. – artlung Aug 12 '10 at 4:45
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.