get_comment_count( int $post_id )

The amount of comments in a post or total comments.


Description Description

A lot like wp_count_comments(), in that they both return comment stats (albeit with different types). The wp_count_comments() actually caches, but this function does not.


Parameters Parameters

$post_id

(int) (Optional) Comment amount in post if > 0, else total comments blog wide.


Top ↑

Return Return

(array) The amount of spam, approved, awaiting moderation, and total comments.


Top ↑

Source Source

File: wp-includes/comment.php

function get_comment_count( $post_id = 0 ) {
	global $wpdb;

	$post_id = (int) $post_id;

	$where = '';
	if ( $post_id > 0 ) {
		$where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
	}

	$totals = (array) $wpdb->get_results("
		SELECT comment_approved, COUNT( * ) AS total
		FROM {$wpdb->comments}
		{$where}
		GROUP BY comment_approved
	", ARRAY_A);

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

	foreach ( $totals as $row ) {
		switch ( $row['comment_approved'] ) {
			case 'trash':
				$comment_count['trash'] = $row['total'];
				break;
			case 'post-trashed':
				$comment_count['post-trashed'] = $row['total'];
				break;
			case 'spam':
				$comment_count['spam'] = $row['total'];
				$comment_count['total_comments'] += $row['total'];
				break;
			case '1':
				$comment_count['approved'] = $row['total'];
				$comment_count['total_comments'] += $row['total'];
				$comment_count['all'] += $row['total'];
				break;
			case '0':
				$comment_count['awaiting_moderation'] = $row['total'];
				$comment_count['total_comments'] += $row['total'];
				$comment_count['all'] += $row['total'];
				break;
			default:
				break;
		}
	}

	return $comment_count;
}

Top ↑

Changelog Changelog

Changelog
Version Description
2.0.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.