
Definition
In WordPress, comment_class() prints a full class attribute for a comment, such as class="comment even thread-even depth-1".
These classes help you style odd and even rows, nested replies, comments from logged-in users, and comments by the post author.
Syntax
Place it inside the opening tag of the comment wrapper. Add your own class if you want.
<li <?php comment_class(); ?>>
<li <?php comment_class( 'my-comment' ); ?>>
$classes = comment_class( '', null, null, false );
| Call | What it does |
|---|
comment_class() | Prints the class attribute for the current comment. |
comment_class( 'my-comment' ) | Adds your own class to the list. |
comment_class( '', null, null, false ) | Returns the class attribute instead of printing it. |
Do not write class="" yourself. The function prints the whole attribute.
Full declaration
comment_class( string|string[] $css_class = '', int|WP_Comment $comment = null, int|WP_Post $post = null, bool $display = true ): void|string
Parameters
| Parameter | Description |
|---|
$css_class | Optional. One or more extra classes to add. |
$comment | Optional. A comment ID or WP_Comment object. Default is the current comment. |
$post | Optional. A post ID or WP_Post object. Default is the current post. |
$display | Optional. true prints the attribute. false returns it. Default true. |
Return Value
| Return Value | Description |
|---|
| void|string | Prints the class attribute when $display is true. Returns it as a string when $display is false. |
WordPress Examples
Three short theme examples. Each one has a sample output.
Example 1 — Default classes
Add the standard comment classes to a list item.
<li <?php comment_class(); ?> id="comment-<?php comment_ID(); ?>">
<li class="comment even thread-even depth-1" id="comment-12">
How It Works
comment marks a normal comment.even and thread-even help with striped rows.depth-1 is the nesting level.
Example 3 — Return instead of print
Use the fourth argument to get the attribute as a string.
<?php $attr = comment_class( 'card', null, null, false ); ?>
<div <?php echo $attr; ?>>
<div class="card comment even thread-even depth-1">
How It Works
- The fourth argument
false stops printing. - The function returns
class="..." as a string. - You can then echo it where you need it.
Frequently Asked Questions
It prints a class attribute with classes such as comment, even or odd, and depth-1.
No. The function prints the full class attribute.
WordPress adds bypostauthor when the comment was written by the author of the post.
Pass it as the first argument, for example comment_class( 'my-comment' ).
Use get_comment_class(). It returns an array of class names.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful