Using WordPress ‘get_comment_class()’ PHP function

The get_comment_class() WordPress PHP function returns the classes for the comment div as an array.

Usage

get_comment_class( string|array $css_class = '', int|WP_Comment $comment_id = null, int|WP_Post $post = null );

Parameters

  • $css_class (string|array) Optional: One or more classes to add to the class list. Default: ''
  • $comment_id (int|WP_Comment) Optional: Comment ID or WP_Comment object. Default current comment. Default: null
  • $post (int|WP_Post) Optional: Post ID or WP_Post object. Default current post. Default: null

More information

See WordPress Developer Resources: get_comment_class

Examples

Basic Usage

Add the get_comment_class() function within the comments loop to output the classes for each comment.

// In your comments loop
$classes = get_comment_class();
echo ' ';
echo implode( ' ', $classes );

Adding Custom Class

Add a custom class to the comment div by providing it as a parameter.

// In your comments loop
$classes = get_comment_class( 'custom-class' );
echo ' ';
echo implode( ' ', $classes );

Adding Multiple Custom Classes

Add multiple custom classes by providing an array of class names.

// In your comments loop
$custom_classes = array( 'custom-class-1', 'custom-class-2' );
$classes = get_comment_class( $custom_classes );
echo ' ';
echo implode( ' ', $classes );

Using a Specific Comment ID

Retrieve classes for a specific comment ID.

// Replace 123 with your desired comment ID
$comment_id = 123;
$classes = get_comment_class( '', $comment_id );
echo ' ';
echo implode( ' ', $classes );

Using a Specific Post ID

Retrieve classes for comments in a specific post.

// Replace 456 with your desired post ID
$post_id = 456;
$classes = get_comment_class( '', null, $post_id );
echo ' ';
echo implode( ' ', $classes );