wp_count_comments()
Retrieve total comments for blog or single post.
The comment stats are cached and then retrieved, if they already exist in the cache.
Uses: get_comment_count()
Hooks from the function
Return
stdClass
. The number of comments keyed by their status.
Usage
wp_count_comments( $post_id );
- $post_id(int)
- Restrict the comment counts to the given post.
Default: 0, which indicates that comment counts for the whole site will be retrieved
Examples
#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
#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
- See: get_comment_count() Which handles fetching the live comment counts.
Changelog
Since 2.5.0 | Introduced. |