Grid layout “last” class to every third item

Seems like a trivial problem but I can’t get it to work. I need to add class="last" to every third post.

Here is my code:

  <?php
     $count = 0;
     $my_query = new WP_Query('cat=-18,-7&showposts=9');
     while ($my_query->have_posts()) : $my_query->the_post();
    ?>

    <article class="<?php if ($count % 3 == 0) { echo "last "; }" ?>> </article>

    <?php 
          $count++;
          endwhile; 
    ?>

Related posts

Leave a Reply

4 comments

  1. I think you just need to start the $count variable from 1 and not zero. You’ll get the opposite effect otherwise because 0 modulo 3 is 0. The first item of every 3 will be getting the class name.

  2. I am not sure what you need mod operator here for, it is usual for keeping track of even/odd values. You simply need every third.

    $i = 0;
    
    //while stuff
        $i++;
        if( 3 == $i ) {
            $i = 0;
            echo 'last';
        }
    
  3. I found this looking for a way to do the same for use with the WordPress starter theme, ‘Bones’. It also has a ‘first’ class. I post that here in case it helps anybody else.

    <div class="wrap clearfix">
    <?php 
    $count = 1;
    $categories = get_categories($args);
    foreach ($categories as $cat) { ?>
        <article class="
            <?php 
                //echo $count.' ';
                if ($count % 3 == 0) {echo 'last ';} 
                if ($count == 1 || $count % 3 == 1) {echo 'first ';}
            ?>fourcol"> 
            <h4><?php echo $cat->cat_name ?></h4>
            <div class="desc"><?php echo $cat->category_description ?></div>
        </article>
    <?php $count++;} ?>