get_comment_count() WordPress Function

The get_comment_count() function is a built-in function in WordPress that allows you to easily get the number of comments a post has. This function is useful if you want to display the number of comments a post has on your website.

get_comment_count( int $post_id ) #

Retrieves the total comment counts for the whole site or a single post.


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.


Top ↑

Return

(int[]) The number of comments keyed by their status.

  • 'approved'
    (int) The number of approved comments.
  • 'awaiting_moderation'
    (int) The number of comments awaiting moderation (a.k.a. pending).
  • 'spam'
    (int) The number of spam comments.
  • 'trash'
    (int) The number of trashed comments.
  • 'post-trashed'
    (int) The number of comments for posts that are in the trash.
  • 'total_comments'
    (int) The total number of non-trashed comments, including spam.
  • 'all'
    (int) The total number of pending or approved comments.


Top ↑

Source

File: wp-includes/comment.php

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

	$comment_count = array(
		'approved'            => 0,
		'awaiting_moderation' => 0,
		'spam'                => 0,
		'trash'               => 0,
		'post-trashed'        => 0,
		'total_comments'      => 0,
		'all'                 => 0,
	);

	$args = array(
		'count'                     => true,
		'update_comment_meta_cache' => false,
	);
	if ( $post_id > 0 ) {
		$args['post_id'] = $post_id;
	}
	$mapping       = array(
		'approved'            => 'approve',
		'awaiting_moderation' => 'hold',
		'spam'                => 'spam',
		'trash'               => 'trash',
		'post-trashed'        => 'post-trashed',
	);
	$comment_count = array();
	foreach ( $mapping as $key => $value ) {
		$comment_count[ $key ] = get_comments( array_merge( $args, array( 'status' => $value ) ) );
	}

	$comment_count['all']            = $comment_count['approved'] + $comment_count['awaiting_moderation'];
	$comment_count['total_comments'] = $comment_count['all'] + $comment_count['spam'];

	return array_map( 'intval', $comment_count );
}


Top ↑

Changelog

Changelog
VersionDescription
2.0.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More