How can I assign a specific id to the last comment of a post

I am fairly new to WordPress and I am currently designing a template for a client of our company. However, I need to assign a specific id to the last comment of a post.

Basically I have my own function that is called on the callback of wp_list_comments().
this is due to the fact that I have a very customised comment layout.

Read More

Now, in the functions.php I would like to assign simply with an if statement such as

if ( is_last_comment() ) : print "last-comment" endif; 

I have looked here and in the codex and on other pages and I cannot find anything.

I appreciate anykind of help.

Thank you very much in advance.

Related posts

Leave a Reply

2 comments

  1. I guess you use the comments loop(?). If so, you could

    Possibility A

    count the comments first, set $i = 0; before the loop and $i++ at the beginning/inside the loop and then attach your needed id when `if ( $count < $i ) $css_id = “id=’last-comment'”.

    Possibility B

    You could take the comments object(?) and use $last_comment = count( $comments_obj ); and after the loop echo $comments->$last_comment;. If it’s an array, you should use echo $comments[ $last_comment ]; of course.


    Not sure which one works as I haven’t dealt with comments for a while, but it should get you on the right track.

  2. I’m sure there’s a way to do it in the comments walker, but if I were approaching the problem I would probably do something like this:

    Add a hook on saving a new comment that updates a “latest comment” flag on its parent post;

    add_action( 'wp_insert_comment', 'set_last_comment', 10, 2 );
    
    function set_last_comment_flag( $id, $comment ) {
        update_post_meta( $comment->comment_post_ID, '_last_comment', $id );
    }
    

    and then, use that flag to filter the comment classes.

    add_filter( 'comment_class', 'flag_last_comment', 10, 4)
    
    function flag_last_comment( $classes, $class, $comment_id, $post_id ) {
        if ( get_post_meta( $post_id, '_last_comment', true ) == $comment_id ) 
            $classes[] = 'last_comment';
    
        return classes;
    }
    

    Now, this flags the last comment written, not necessarily the bottom one as displayed on the page (you could have threaded comments, or multiple page of comments on a post). So I don’t know how well it would work for you.

    If you have to target the last comment displayed on the page, I would really just use javascript to apply whatever class you want to it. The logic required to figure that out from the comment walker would probably be a lot more complex than a single line of jQuery to go back after the page has rendered and find the last list item.