Support » Fixing WordPress » Add a class based on even or odd post

  • Resolved blicht454


    Hello, I’m trying to add a class to a blog post based on whether the post is an even or odd number. It’s almost working–the class is being echoed–but I think I’ve made a mistake in editing the loop because now only two posts will show up on blog home page. Does anyone have any ideas?

    Here’s the code I’m using:

    Like I said, everything is working except for the fact that I’m only given two posts, even though I have published six.

    Thanks for your help!

Viewing 3 replies - 1 through 3 (of 3 total)
  • I believe that your endif is misplaced. Try moving it like this:

    if( ($postcount % 2) == 0 ) :
                            echo " class=\"even\"";
                    elseif ( ($postcount % 2) != 0 ):
                            echo " class=\"odd\"";

    However, the id attribute really should be unique within a document. If you don’t need the extra div, you can add the class like this:

    <?php $postcount++;
    $new_class = ( ($postcount % 2) == 0 ) ? "even" : "odd"; ?>
    <div <?php post_class($new_class) ?> id="post-<?php the_ID(); ?>">
       // posts go here

    Don’t forget to take out the extra ending div tag and the endif line.

    Great! Thanks for your help!

    is_int($postcount/2) will work as well.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Add a class based on even or odd post’ is closed to new replies.