Cleanest Way to Select Every Second Element in a Loop?

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>

Leave a Comment