WordPress.org

Ready to get started?Download WordPress

Forums

Add CSS code to list item for every 3rd loop in WP (3 posts)

  1. sincewelastspoke
    Member
    Posted 2 years ago #

    Hi,

    I have this code:

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

    Now after every 3rd loop, I'd like to add style="background:red" to my list item.

    How do I do this?

  2. cubecolour
    ɹoʇɐɹǝpoɯ
    Posted 2 years ago #

    You can do this most easily with css – if the people viewing your site are likely to be using decent browsers

    li:nth-child(3n+0) {background: #900;}

  3. sincewelastspoke
    Member
    Posted 2 years ago #

    Brilliant.

    Thank you.

    I also got this PHP solution:

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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags