Add Odd And Even Class to WordPress Posts

How to Add Odd And Even Class to WordPress Posts

in Posts & pages
Google+ LinkedIn

Often when designing a WordPress theme, designers choose to have different styling for odd/even comments. But recently while working on a project, I required to style odd and even blog posts differently. To do this, I needed to add odd and even class to WordPress posts. While searching for a solution, I found many tutorials on how to add odd and even classes to blog posts markup. Most of them are using PHP incrementing operators inside the loop and checking the reminder of the incremented number. If the incremented number has zero reminder the post is even, otherwise it’s odd.

While that’s a good idea, But I followed a little different approach. And In this tutorial I am going to show you how I added odd and even classes to blog posts in WordPress Theme. This following function does exactly what we want.

Insert this into your theme’s functions.php will give each of the posts on blog page add odd and even classes accordingly that can be styled as you prefer in your style.css.

// add odd and even class to wordpress posts
function oddeven_post_class ( $classes ) {
    global $current_class;
    $classes[] = $current_class;
    $current_class = ( $current_class == 'odd' ) ? 'even' : 'odd';
    return $classes;
}
add_filter ( 'post_class' , 'oddeven_post_class' );
global $current_class;
$current_class = 'odd';

Share the love

If you like this snippet, share it with others!

Leave a Reply

Your email address will not be published. Required fields are marked *