wp_count_comments()WP 2.5.0

Gets data about the number of comments on the site or separately for the specified post. Data is collected separately by comment types (all variants of the field comment_approved: approved, spam, etc.).

If you need to get the number of posts (published, drafts, pending, etc.), use wp_count_posts().

Hooks from the function

Returns

stdClass. An object with values:

stdClass Object
(
	[approved] => 49
	[total_comments] => 49
	[moderated] => 0
	[spam] => 0
	[trash] => 0
	[post-trashed] => 0
)

Usage

wp_count_comments( $post_id );
$post_id(integer)
ID of the post for which you need to get comment data.
Default: 0

Examples

0

#1 Get the number of comments for the all site:

$comments_count = wp_count_comments();

$lines = [ 'Site comment statistics: ' ];
$lines[] = sprintf( 'In moderation: %s', $comments_count->moderated );
$lines[] = sprintf( 'Approved: %s', $comments_count->approved );
$lines[] = sprintf( 'Marked as spam: %s', $comments_count->spam );
$lines[] = sprintf( 'Comments in cart: %s', $comments_count->trash );
$lines[] = sprintf( 'Total comments: %s', $comments_count->total_comments );

echo implode( '<br>', $lines );

As a result, the following information will be displayed on the screen:

Site comment statistics:
In moderation: 0
Approved: 4973
Marked as spam: 223
Comments in cart: 4
Total comments: 4975
0

#2 Get the comment statistics for a particular post:

$comments_count = wp_count_comments( 140 );

$lines = [ 'The post comment statistics: ' ];
$lines[] = sprintf( 'In moderation: %s', $comments_count->moderated );
$lines[] = sprintf( 'Approved: %s', $comments_count->approved );
$lines[] = sprintf( 'Marked as spam: %s', $comments_count->spam );
$lines[] = sprintf( 'Comments in cart: %s', $comments_count->trash );
$lines[] = sprintf( 'Total comments: %s', $comments_count->total_comments );

echo implode( '<br>', $lines );

We get it:

The post comment statistics:
In moderation: 0
Approved: 49
Marked as spam: 0
Comments in cart: 0
Total comments: 49

Notes

Changelog

Since 2.5.0 Introduced.

wp_count_comments() code WP 6.8.3

function wp_count_comments( $post_id = 0 ) {
	$post_id = (int) $post_id;

	/**
	 * Filters the comments count for a given post or the whole site.
	 *
	 * @since 2.7.0
	 *
	 * @param array|stdClass $count   An empty array or an object containing comment counts.
	 * @param int            $post_id The post ID. Can be 0 to represent the whole site.
	 */
	$filtered = apply_filters( 'wp_count_comments', array(), $post_id );
	if ( ! empty( $filtered ) ) {
		return $filtered;
	}

	$count = wp_cache_get( "comments-{$post_id}", 'counts' );
	if ( false !== $count ) {
		return $count;
	}

	$stats              = get_comment_count( $post_id );
	$stats['moderated'] = $stats['awaiting_moderation'];
	unset( $stats['awaiting_moderation'] );

	$stats_object = (object) $stats;
	wp_cache_set( "comments-{$post_id}", $stats_object, 'counts' );

	return $stats_object;
}
1 comment