michaelmcgurk
michaelmcgurk

Reputation: 6519

Add CSS code to every 3rd iteration of loop - WordPress

I'd like to add a style="background:green" for every 3rd iteration of this WP loop.

How do I achieve this?

   if( have_posts() ) :
    while ($wp_query->have_posts()) : $wp_query->the_post();
    ?>
    <li>Test</li>
    <?php endwhile; ?>
    <?php endif;

Many thanks for any pointers.

Upvotes: 1

Views: 642

Answers (2)

danjah
danjah

Reputation: 3059

Maybe an incrementing variable and usage of the modulus operator, just an idea. http://php.net/manual/en/language.operators.arithmetic.php, something similar for WP: http://www.ilovecolors.com.ar/ads-wordpress-loop/

Upvotes: 0

Alex Hadley
Alex Hadley

Reputation: 2125

Have you tried using the % operator. Something like the following (untested):

if( have_posts() ) :
$i=0;
while ($wp_query->have_posts()) : $wp_query->the_post();
$i++;
?>
<li <?php if(($i % 3)==0)echo 'style="background:green"';?>>Test</li>
<?php endwhile; ?>
<?php endif;

PHP reference: http://php.net/manual/en/language.operators.arithmetic.php

Upvotes: 5

Related Questions