How to select every second element in a loop?


#1

Hi guys,

I’m not perfect in PHP so I need your help :). I have a WP loop, something like this:

    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  • <?php the_content(); ?>
  • <?php endwhile; ?> <?php endif; ?>

Can anybody tell me how can I select every second li element and add to them a class (“clearfix”, to clear a floating)?

Thank you in advance, - Alex


#2

You could try putting in a counting variable that you increment with every pass, and then inside, you have if statement to see if it’s every other or not… something like this…

<?php $i = 1; ?>
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php if($i%2 == 0) : ?>
  • <?php the_content(); ?>
  • <?php else : ?>
  • <?php the_content(); ?>
  • <?php endif; ?> <?php $i++; ?> <?php endwhile; ?> <?php endif; ?>

#3

Edit: ThemeBlvd was faster :slight_smile:


#4

correct statement is

if($i%2 == 0)

with two! equal sign :wink:

or

if(!$i%2)

works too


#5
    <?php $k = 1; ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  • <?php the_content(); ?>
  • <?php $k++; ?> <?php endwhile; ?> <?php endif; ?>

EDIT: Jason beat us all :slight_smile:


#6
revaxarts said

correct statement is

if($i%2 == 0)

with two! equal sign :wink:

or

if(!$i%2)

works too

Sorry, TF discussion board is not the best code editor, fixed :slight_smile:


#7

Thanks everyone for so quick replies! I’ll try to employ it now :slight_smile:


#8

This thread gave me an idea. If you’ve ever used Smarty templates, loops have certain variables automatically set for index (zero-based), iteration (1 based), even, odd, first, and last. These are very useful or setting classes, changing styles, alternating colors, etc. It just occurred to me that Wordpress could easily have this functionality within The Loop by wrapping have_posts() in a custom function:

function super_have_posts() {
     global $first, $last, $index, $iteration, $even, $odd;

     ...calculate all your variables here, account for multiple loops, etc...

     if(have_posts()) {
          return true;
     }
}

then you would just use while(super_have_posts()) in your loop. What do you guys think?