I am currently using this little loop to display a list of posts using the "events" custom post type

<?php global $post; // required
    $args = array('post_type' => 'events');
    $custom_posts = get_posts($args);
    foreach($custom_posts as $post) : setup_postdata($post);

<ul><li class="post">Content goes here</li></ul>

<?php endforeach; ?>

What I want to do is add a class to every other list item so that I can style them alternatively (One white, one black, one white, one black, for example)

I've done this before with a standard loop but I'm only just converting over to get_posts so I'm a bit stuck.

Any help would be great.

Thanks in advance

  • 2
    possible duplicate of How to mark every 3rd post
    – kaiser
    Commented Mar 15, 2012 at 14:04
  • Take a look at this ↑ Q. It's not every third, but you can just exchange 3 with 2.
    – kaiser
    Commented Mar 15, 2012 at 14:04

3 Answers 3


A simple solution would be to add an alternating class to every other post in the list. In particular, (in your style.css) style the list elements <li> in one particular way, and then over-ride that style for list elements of a particular class <li class='my-alternate-class'>. The class my-alternate-cass will applied to every other list element:

<?php global $post;
    $args = array('post_type' => 'events');
    $custom_posts = get_posts($args);
         <?php foreach($custom_posts as $post) : setup_postdata($post);?>
              <?php $class = (empty($class) ? "class='my-alternate-class'" : "");?>
              <li <?php echo $class;?>>Content goes here</li>
         <?php endforeach; ?>
    <?php endif; ?>
    //Remember to wp_reset_postdata() afterwards

Please note this untested.

I've also added wp_reset_postdata() as otherwise your site might break.


I know a CSS3 solution:

li {background: #000;}
li:nth-child(odd) {background: #fff;}

The same can be achieved with jQuery, where #eventlist is the id of your unordered list:

  jQuery('#eventlist li:nth-child(odd)').addClass('alternate');

And then: .alternate {background: #fff;}

$counter = 0; // Reset counter before the loop
$thenumber = ( $counter%2 ) + 1; // Set counter reset (every 2nd count in this example)
$counter++; // Increment number

echo $thenumber; // Echoes 1, 2, 1, 2, 1, 2 and so on...

This could be used like this:

<li class="post postCount<?php echo $thenumber; ?>">Content goes here</li>

so that you get

<li class="post postCount1"></li>
<li class="post postCount2"></li>
<li class="post postCount1"></li>

Hope this works!

(by the way, you might want to move the <ul> tags outside the loop, so that you have only one list with the list items looping inside)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.