Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

At the moment I'm using this strange method:

<ul>
<?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; ?>
</ul>

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
add comment

1 Answer

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:

<ul>
  <?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; ?>
</ul>
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
add comment

Your Answer

 
discard

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.