6

I need to add a "last" class to the last post that appears in loop.php.

Can someone tell me how to accomplish this?

2 Answers 2

12

assuming you're using post_class():

add_filter('post_class', function($classes){
  global $wp_query;

  if(($wp_query->current_post + 1) == $wp_query->post_count)
    $classes[] = 'last';

  return $classes;
});
2
  • Does this work for the absolute last post in a paginated loop? Commented Oct 19, 2014 at 22:42
  • I think it should be $found_posts instead. Codex Screenshot Commented Aug 12, 2015 at 17:12
1

I am using jQuery addClass() when I style odd/even list items or similar. You could probably use it to achieve what you want too.

Example:

 $("#menu_side > ul > li:last-child").addClass("last");
1
  • Thanks for the response, but I'm not using jQuery. Also, using JavaScript to apply the class could cause the styling to display before the JavaScript loads, which would make it "flash off" and it wouldn't look pretty.
    – user1462
    Commented Jan 20, 2011 at 21:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.