WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Add a class based on even or odd post (4 posts)

  1. blicht454
    Member
    Posted 2 years ago #

    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:

    http://pastebin.com/XBeYbArS

    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!

  2. vtxyzzy
    Member
    Posted 2 years ago #

    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\"";
                    endif;
                    ?>>

    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.

  3. blicht454
    Member
    Posted 2 years ago #

    Great! Thanks for your help!

  4. eteich
    Member
    Posted 2 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic