1

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.

0

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.