Add CSS Classes to WordPress Loop Items to Build More Flexible Layouts

When developing WordPress themes, we often need to add CSS classes to posts in archive loops so we can build different layouts. In the example below, we want a four-column image layout. We float the items left, give each image a width of 23.5%, and use a 2% right margin. The last image in each row has no right margin. That makes each row exactly 100% wide: 23.5% x 4 + 2% x 3.

Add CSS classes directly in the theme loop markup

To create that style, we need to add a last class to the final image in each row, meaning the 4th, 8th, 12th, and other items whose position can be divided evenly by 4.

<?php $i=1; ?>
<?php while ( have_posts() ) : the_post(); ?>
    <li class="<?php echo ($i%4 == 0) ? "last": ""; $i++; ?> ">
        <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
            <?php if ( has_post_thumbnail() ) { the_post_thumbnail('full'); } ?>
        </a>
    </li>
<?php endwhile; ?>

Then use CSS to set the right margin of images with the last class to 0.

.imgs li {
  width: 23.5%;
  margin-right: 2%;
  float: left;
}
.imgs li.last{
  margin-right: 0;
}

The implementation above is very direct. If the site structure is simple and only one place needs this layout, that approach is fine. But if the site needs the same layout in many places, the method above requires you to duplicate the same logic repeatedly, which violates the DRY principle. In fact, we can use a WordPress filter to add the last class directly to each post item in the loop.

Add CSS classes through the post_class filter

function additional_post_classes( $classes ) {
	global $wp_query;
	if( $wp_query->current_post % 4 ) {
		$classes[] = 'last';
	} else {
		$classes[] = 'post-odd';
	}
	return $classes;
}
add_filter( 'post_class', 'additional_post_classes' );

The idea is simple: before the post markup is output, check the position of the post in the loop. When it matches the condition, add the last class to that item. After you copy the code into functions.php, the class is added automatically, which is much more convenient.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *