comment_class

Home » Hooks » comment_class

The WordPress hook comment_class is used to add custom classes to each comment displayed on a website. These classes can be used to style comments differently based on certain criteria, such as the author of the comment or its status.

The comment_class hook is very useful for developers who want to customize the appearance of comments on a WordPress website. By adding custom classes to each comment, developers can create unique designs that stand out from the default appearance.

For example, let’s say you want to change the color of comments made by the post author. You could use the comment_class hook to add a custom class to these comments, such as comment-by-author, and then use CSS to style the comments differently.

Here’s an example usage code for the comment_class hook:

function custom_comment_classes($classes, $class, $comment_id, $post_id) {
  $comment = get_comment($comment_id);
  if ($comment->user_id === get_post_field('post_author', $post_id)) {
    $classes[] = 'comment-by-author';
  }
  return $classes;
}
add_filter('comment_class', 'custom_comment_classes', 10, 4);

In this example, we’re using the custom_comment_classes function to add the comment-by-author class to comments made by the post author. We’re doing this by checking if the comment’s user_id matches the post_author of the current post. If they match, we add the custom class to the $classes array and return it. Finally, we use the add_filter function to apply this filter to the comment_class hook.

Learn More on WordPress.org

WordPress snippets using the comment_class hook

Register an account to save your snippets or go Pro to get more features.