WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

What's the quickest and easiest way to select every second element in the loop?

At the moment I'm using this strange method:

<?php $k = 1; ?>
  <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <li class="<?php if($k%2 == 0) echo 'last'; ?>"><?php the_content(); ?></li>
<?php $k++; ?>
<?php endwhile; ?>
<?php endif; ?>

Can't use nth-child since IE doesn't support it and CSS3 PIE isn't playing nice with my site at the moment.

share|improve this question
up vote 6 down vote accepted

I wouldn't consider that strange :). WordPress uses a similar method to apply the 'alternate' class to every other row in the tables on the admin page, something like:

  <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
     <?php $class = (empty($class) ? 'class="alternate"' : '');?>
     <li <?php echo $class; ?> ><?php the_content(); ?></li>
  <?php endwhile; ?>
  <?php endif; ?>
share|improve this answer
Good to know. Thank you! Sorry I can't vote up your answer, I haven't got 15+ reputation at the moment. You've got my vote though. – realph Apr 2 '12 at 23:11
You can always 'accept' answers (clicking the tick to the left) :). I'd encourage you to do so - it clears your question off the 'unanswered' pile and means others can quickly identify a 'correct' answer. – Stephen Harris Apr 2 '12 at 23:28
Ahh, cheers! I didn't even see that there. – realph Apr 2 '12 at 23:37

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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