Using WordPress ‘wp_list_comments()’ PHP function

The wp_list_comments() WordPress PHP function is used to display a list of comments for a particular post. This function is typically used within the comments.php template.

Usage

A simple usage of the function could be:

<div>
wp_list_comments();
</div>

In this case, it will display all the comments for the current post without any customization.

Parameters

  • $args (string|array) – Optional. Formatting options.
  • $comments (WP_Comment[]) – Optional. Array of WP_Comment objects.

More information

See WordPress Developer Resources: wp_list_comments()

Examples

Customizing Checkbox Field

$comment_form = array(
'fields' => array(
'cookies' => '<p class="comment-form-cookies-consent">
<input id="wp-comment-cookies-consent" name="wp-comment-cookies-consent" type="checkbox" value="yes"' . $consent . ' />
<label for="wp-comment-cookies-consent">' . __( 'Save my name, email, and website in this browser for the next time I comment.' ) . '</label>
</p>',
),
);
comment_form( $comment_form );

This code creates a custom form for adding comments. It includes a checkbox for user’s consent to save their name, email, and website.

Displaying Comments Only with Custom Comment Display

<ul class="commentlist">
wp_list_comments( 'type=comment&callback=mytheme_comment' );
</ul>

This code will only display comments (excluding pingbacks or trackbacks), using a custom callback function mytheme_comment to control how each comment is displayed.

Custom Comment Display Callback Function

function mytheme_comment($comment, $args, $depth) {
if ( 'div' === $args['style'] ) {
$tag = 'div';
$add_below = 'comment';
} else {
$tag = 'li';
$add_below = 'div-comment';
}
echo '<',$tag,' ',comment_class(empty($args['has_children']) ? '' : 'parent'),' id="comment-',comment_ID(),'">';
if ( 'div' != $args['style'] ) {
echo '<div id="div-comment-',comment_ID(),'" class="comment-body">';
}
// Rest of the function...
}

This callback function mytheme_comment is a custom way of controlling how each comment is displayed. It includes conditional checks and formatting based on whether the comment has child comments.

Please note that the closing tag is not included at the end of the function, as WordPress will add the appropriate closing tag after listing any child elements.

Reverse Order of Comments

wp_list_comments( array(
'reverse_top_level' => true
) );

This example will display the newest comments first by reversing the order of top-level comments.

Displaying Comments with HTML5 Format

wp_list_comments( array(
'format' => 'html5'
) );

This example shows how to display comments using HTML5 markup format. If the theme doesn’t support HTML5, it will default to XHTML.