Using WordPress ‘comment_class’ PHP filter

The comment_class WordPress PHP filter modifies the returned CSS classes for the current comment.

Usage

add_filter('comment_class', 'your_function_name', 10, 5);
function your_function_name($classes, $css_class, $comment_id, $comment, $post) {
    // your custom code here
    return $classes;
}

Parameters

  • $classes (string[]): An array of comment classes.
  • $css_class (string[]): An array of additional classes added to the list.
  • $comment_id (string): The comment ID as a numeric string.
  • $comment (WP_Comment): The comment object.
  • $post (int|WP_Post): The post ID or WP_Post object.

More information

See WordPress Developer Resources: comment_class

Examples

Add a custom class to comment

Add a custom class ‘custom-comment’ to every comment.

add_filter('comment_class', 'add_custom_comment_class', 10, 5);
function add_custom_comment_class($classes, $css_class, $comment_id, $comment, $post) {
    $classes[] = 'custom-comment';
    return $classes;
}

Highlight author’s comments

Add a ‘comment-author’ class to comments made by the post author.

add_filter('comment_class', 'highlight_author_comments', 10, 5);
function highlight_author_comments($classes, $css_class, $comment_id, $comment, $post) {
    $post = get_post($post);
    if ($comment->user_id === $post->post_author) {
        $classes[] = 'comment-author';
    }
    return $classes;
}

Add odd and even classes

Add ‘odd’ and ‘even’ classes to alternate comments for styling purposes.

add_filter('comment_class', 'add_odd_even_classes', 10, 5);
function add_odd_even_classes($classes, $css_class, $comment_id, $comment, $post) {
    global $comment_alt;
    $comment_alt = (isset($comment_alt) ? $comment_alt : 0) + 1;
    $classes[] = ($comment_alt % 2) ? 'odd' : 'even';
    return $classes;
}

Add class based on comment depth

Add a class ‘depth-X’ where X is the depth of the comment.

add_filter('comment_class', 'add_comment_depth_class', 10, 5);
function add_comment_depth_class($classes, $css_class, $comment_id, $comment, $post) {
    $depth = intval($comment->comment_parent) > 0 ? get_comment_depth($comment_id) : 1;
    $classes[] = 'depth-' . $depth;
    return $classes;
}

Remove specific class from comments

Remove the ‘comment’ class from all comments.

add_filter('comment_class', 'remove_comment_class', 10, 5);
function remove_comment_class($classes, $css_class, $comment_id, $comment, $post) {
    $classes = array_diff($classes, array('comment'));
    return $classes;
}