The comment_class() WordPress PHP function generates semantic classes for each comment element.
Usage
Here’s an example of how you might use the function:
<li <?php comment_class('custom-class'); ?> id="li-comment-<?php comment_ID(); ?>">
In this example, comment_class()
is used to add a custom class (‘custom-class’) to a list item that represents a comment. The ID of the list item is set to ‘li-comment-‘ followed by the ID of the comment.
Parameters
- $css_class (string|string[]) Optional – One or more classes to add to the class list. Default: ”
- $comment (int|WP_Comment) Optional – Comment ID or WP_Comment object. Default: null
- $post (int|WP_Post) Optional – Post ID or WP_Post object. Default: null
- $display (bool) Optional – Whether to print or return the output. Default: true
More information
See WordPress Developer Resources: comment_class()
This function has been implemented since WordPress 2.7.0. It allows you to add custom CSS classes to comments in your theme, making it easier to style different parts of the theme in different ways.
Examples
Adding a custom class
Add a custom CSS class to a comment.
<li <?php comment_class('custom-class'); ?> id="li-comment-<?php comment_ID(); ?>">
Multiple classes
Add multiple custom classes to a comment.
<li <?php comment_class(['custom-class1', 'custom-class2']); ?> id="li-comment-<?php comment_ID(); ?>">
Specify a comment
Add a class to a specific comment.
<li <?php comment_class('custom-class', $comment_id); ?> id="li-comment-<?php comment_ID(); ?>">
Specify a post
Add a class to a comment in a specific post.
<li <?php comment_class('custom-class', null, $post_id); ?> id="li-comment-<?php comment_ID(); ?>">
Return the output
Return the output instead of printing it.
<?php $class = comment_class('custom-class', null, null, false); echo "<li class='{$class}' id='li-comment-".comment_ID()."'>"; ?>
In this example, the comment_class()
function is called with the $display parameter set to false, which causes the function to return the class string instead of printing it. The returned class string is then used when generating the list item HTML.