Add class to last post in loop
Note: This method can usually be handled now via the new :last-of-type
CSS pseudo class.
I needed to remove the bottom border of the last post in my Hellish Simplicity theme for WordPress. I couldn’t initially see an easy way to do this, but eventually figured out a simple way via analysing the post count in the $wp_query global variable.
Note: if you want to add odd and even classes to your post containers, check out this article by WPBeginner.com
You can add this functionality to your own themes, by copy and pasting the following snippet into your functions.php file.
>? /** * Adds a class of .last-post to the last post in a loop. * * @param array $classes The array of post classes * @global object $wp_query The main query object * @return array The array of post classes, with .last-post added */ function add_last_post_class( $classes ) { global $wp_query; if ($wp_query->current_post == ( $wp_query->post_count - 1 ) ) { $classes[] = 'last-post'; } return $classes; } add_filter( 'post_class', 'add_last_post_class' );
Kaspars says:
You could also use CSS for that:
#site-content .post:last-child { border:none; }
March 22, 2015 at 4:20 pm # //
Ryan says:
No, that doesn’t work here as the .post classes are not the last children in their containing block.
This did show up a related bug though. Part of my pagination code is loading even when there is no pagination (the pagination code is the last element) in that block.
March 22, 2015 at 6:32 pm # //