帖子或总评论中的评论数量。

原型

get_comment_count( int $post_id )

描述

很像wp_count_comments(),因为它们都返回注释统计数据(尽管有不同的类型)。 wp_count_comments()实际上是缓存的,但是这个函数没有。

参数

$post_id (int) (Optional)  如果> 0,评论金额在帖子中,否则博客评论总数。

返回值

(array)  垃圾邮件数量,已批准,等待审核以及总评论数。

源文件

路径:wp-includes/comment.php

<?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;
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/get_comment_count/