Using WordPress ‘get_comment_count()’ PHP function

The get_comment_count() WordPress PHP function retrieves the total comment counts for the whole site or a single post.

Usage

get_comment_count( $post_id );

Example:
Input: get_comment_count(42);
Output: Array with comment counts for post with ID 42

Parameters

  • $post_id (int) Optional: Restrict the comment counts to the given post. Default 0, which indicates that comment counts for the whole site will be retrieved.

More information

See WordPress Developer Resources: get_comment_count()

Examples

Get comment count for a specific post

Get the comment count for a post with ID 42.

$post_id = 42;
$comment_count = get_comment_count($post_id);
echo 'Comment count for post 42: ' . $comment_count['approved'];

Display total comment count for the whole site

Get the total comment count for the entire site.

$comment_count = get_comment_count();
echo 'Total comment count for the site: ' . $comment_count['approved'];

Display comment count for a post in a loop

Display the comment count for each post while looping through posts.

while (have_posts()) {
    the_post();
    $post_id = get_the_ID();
    $comment_count = get_comment_count($post_id);
    echo 'Comment count for post ' . $post_id . ': ' . $comment_count['approved'];
}

Display approved and unapproved comment count for a post

Display both approved and unapproved comment counts for a post with ID 42.

$post_id = 42;
$comment_count = get_comment_count($post_id);
echo 'Approved comments: ' . $comment_count['approved'];
echo 'Unapproved comments: ' . $comment_count['total_comments'] - $comment_count['approved'];

Display comment count for a post with a custom message

Display the comment count for a post with ID 42, along with a custom message.

$post_id = 42;
$comment_count = get_comment_count($post_id);
echo "There are " . $comment_count['approved'] . " comments on post " . $post_id . ".";