get_comment_count()

最后更新于:2021-11-26 08:37:20

get_comment_count( int$post_id)

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

参数

$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.

响应

(array()) 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.

源文件

文件: gc-includes/comment.php

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

	$post_id = (int) $post_id;

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

	$totals = (array) $gcdb->get_results(
		"
		SELECT comment_approved, COUNT( * ) AS total
		FROM {$gcdb->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 array_map( 'intval', $comment_count );
}