27 April, 2013 โ€” Snippets, WordPress โ€”

Add Custom Class to last Post in WordPress Loop

Just sometimes you might need to add a custom class to the last post in a loop. This might be used to remove a css margin-bottom to a less deep value.

Show me the code

First you will need to add a small function to your functions.php file in your theme directory.

function my_post_class($classes){
    global $wp_query;
    if(($wp_query->current_post+1) == $wp_query->post_count) $classes[] = 'last';
    return $classes;
}
add_filter('post_class', 'my_post_class');

This function will run every time WordPress loads a new post and when it gets to the total number for that page it will add the class of last to the class array.

Next you will need to make sure you have the following code in your post loop. If you don’t have this your classes will not appear in your post.

<div id="blog-post-<?php the_ID(); ?>" <?php post_class(); ?>>

If you need to add more classes to every post you can do so by adding the following line between the if statement and the return function.

$classes[] = 'rounded';

So your code would becomeโ€ฆ

function my_post_class($classes){
    global $wp_query;
    if(($wp_query->current_post+1) == $wp_query->post_count) $classes[] = 'last';
    $classes[] = 'rounded';
    return $classes;
}
add_filter('post_class', 'my_post_class');

This will then add “rounded” to every post class and last to ONLY the last post in the loop.

I hope this helps someone out there. If you have any snippets of your own please post them in the comments below.

Photo Credit: Daveynin