Beginner's Guide for WordPress - Start your WordPress Blog in minutes.
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

How to Add Odd/Even Class to Your Post in WordPress Themes

Last updated on by
Special WordPress Hosting offer for WPBeginner Readers
How to Add Odd/Even Class to Your Post in WordPress Themes

Often when designing a WordPress theme, designers choose to have different styling for odd/even comments. Recently while working on a design, we decided to have different styling for odd/even posts. To do this, we needed to add an odd/even class to appropriate posts. Sadly, this is not one of the default classes. In this article, we will show you how to add an odd/even class to your posts in WordPress Themes.

Simply paste the following code in your theme’s functions.php file

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';

Now simply style the odd/even class differently. You are good to go.

Source: Kevin Chard


Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Page maintained by Syed Balkhi.

WPBeginner's Video Icon
Our HD-Quality tutorial videos for WordPress Beginners will teach you how to use WordPress to create and manage your own website in about an hour. Get started now »

Comments

  1. onkar says:

    how to add odd even class in posts for particular page

  2. Bucur says:

    Ok good function, but css style?

    . post {
    / / Rest of the css
    }

    .odd { } ???

  3. Simon says:

    Thanks for this. Just what I needed.

  4. Samuel says:

    How could I take this a step further and target a specific post category?

    I have a custom post type – testimonial, and I only want odd/even styling in that section.

    Thanks!

  5. Eric says:

    This is by far the easiest method of creating odd and even posts for wordpress!! Thanks so much for sharing!

  6. Christine says:

    As, sadly, css3 selectors are not well supported by all browsers…

    I just tried your code for a new twenty eleven child theme i’m customizing, it works so fine,

    Thanks a Lot for sharing this ! !

  7. Daniele Zamboni says:

    What is odd/even class ? Sorry but i’m newbie

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.