Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

General Discussion

Joseph McClellan
Joseph McClellan
4,045 Points

PHP loop question

I'm outputting some photos with a php loop and I'd like to assign a css class to every 8th image that is output. I'm not 100% certain how to go about doing this. Any ideas?

I already have a loop implemented to do something with the 32nd image outputted at which point the loop cuts out... here's my code thus far.. oh this is using wordpress as the CMS.

$speakers_image_loop = new WP_Query( $args ); $count = 0; while ( $speakers_image_loop->have_posts() ) : $speakers_image_loop->the_post(); ?>

<?php $count++; ?> <!-- increment the count variable -->

<?php the_post_thumbnail();?>

<?php if ($count == 32) : ?> <!-- output goes here --> <?php else : ?><?php endif; ?> <!-- that's the end of the loop interrupt -->

<?php // Loop ends endwhile; // Reset the query wp_reset_postdata();
?>

So I figure I can just use the count variable and call it on the 8th, 16th and 24th image to be output. It's probably an easy solution, but it's evading me.

3 Answers

A couple of options for you:

Using Only CSS If you are looking to add a class for styling, use CSS (following example does not work non-modern browsers)

div img:nth-child(8n) {
    /* CSS class you wish to add*/
}

CSS-Tricks

Using PHP If you are looking to add the class for reasons other than styling (or for styling in older browsers) the following may help (it uses the modulus operator):

    <?php
// the following goes inside your loop

// increment your counter
++$count;

// used a "switch" statement in case you need to add more items, you could also use an "if" statement
switch (true) {

    // this first, as switch() only executes one item per run
    case (32 === $count):
        // code here for your last item
        break;

    // every 8th item
    case (0 === ($count % 8)):
        echo '<img src="/img/whatever.jpg" alt="alt content" class="eighthItem">
        break;
}
?>

PHP Math page

Joseph McClellan
Joseph McClellan
4,045 Points

I had it working for a while with CSS, then it broke. I figured out what went wrong -- added an 'a' tag before the image. Just had to update the css to be

div a:nth-child(8) img {
    /* css class *
}
Joseph McClellan
Joseph McClellan
4,045 Points

I still need to use the loop for something else, but at least this little problem is fixed. Thanks!