I need to add a different class for last post of a Custom Post Type. Is it possible?

I have found this code, but it works only in posts

function wpc_last_post_class( $classes ) {
    global $wp_query;  
    if(($wp_query->current_post+1) == $wp_query->post_count) $classes[] = 'last'; // change the class name  you would like to add here  
    return $classes;  
add_filter('post_class', 'wpc_last_post_class');
  • Do you use the post_class() function in the template file responsible for displaying the custom post type? – nmr May 24 '19 at 20:40
  • 1
    You could try the accepted method here - stackoverflow.com/questions/9610985/… – Faye May 24 '19 at 21:48
  • There's no reason this wouldn't work on a custom post type, unless you're not using post_class() in your template, or you're not using the main query. – Jacob Peattie May 25 '19 at 5:52

Not exactly what you asked for, but given that classes are primarily used for styling, might you consider using CSS pseudo-class ":last-child" instead of PHP code?

Here's some information on how to style using :last-child


| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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