Support » Plugins » Hacks » Add class based on even/odd

  • Resolved Ann-Sophie


    Hi all,

    I’ve created a new custom post type and want to have these listed on a certain page.
    I created a zebra striping for this but obviously this doesn’t work in IE8. How can I dynamically add a class “even” to the posts?

    This is my code:

    					$args = array(
    						'post_type' => 'tarieven',
    						'posts_per_page' => '50',
    						'categorie' => 'dames' );
    					$loop = new WP_Query( $args );
    					while ( $loop->have_posts() ) : $loop->the_post(); ?>
    						<dt class="dienst"><?php the_title(); ?><small class="prijs">€&nbsp;<?php echo get_post_meta($post->ID, 'prijs', true) ?></small></dt>
    						<dd class="omschrijving"><?php the_content(); ?></dd>
    				<?php endwhile; ?>

Viewing 6 replies - 1 through 6 (of 6 total)
  • Moderator bcworkz


    I’m assuming you want the even class added to alternate posts? You could replace the <dl> block contents with something like this:

    if ($stripe) {
      echo '<div class="even">';
      $stripe = false;
      echo '<div class="odd">';
      $stripe = true;
    /* All the remaining loop stuff goes here starting with <dt class=dienst"> and ending with... */
    <?php the_content(); ?></dd></div>

    Tweak as needed for your exact needs. To be complete, you should add $stripe = false; before the while loop. This starts with odd first, simply set to true instead for even first.



    Forum Moderator

    to add the ‘odd/even’ class to the <dl>, try:

    <dl class="<?php echo ($loop->current_post%2 == 0?'odd':'even'); ?>">


    both options work!

    Thanks for that!!!

    I am trying to accomplish the same thing with my custom posts, but can’t seem to translate those answers into my code. I’d like the odd-numbered posts to be styled differently than the even-numbered posts. Here’s my code:

    <?php $args = array( 'post_type' => 'book', 'posts_per_page' => 3 );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
            echo '<div class="entry-content">';
            echo '</div>';
    endwhile; ?>

    I guess I need to add an additional class (.odd or .even) to my div. Right?




    Forum Moderator

    just ‘odd/even’ for three posts might not be enough;

    (I already posted some related suggestion in your other topic:
    I’ll repost a precise suggestion to match your code there.)

    if you insist on using just ‘odd/even’, here is the edited div:

    echo '<div class="entry-content' . ($loop->current_post%2 == 0?' odd':' even') . '">';


    Thanks so much, that worked perfectly! 🙂

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