get_comment_count()
云策文档标注
概述
get_comment_count() 函数用于获取整个站点或指定文章的评论统计数量。它返回一个数组,包含按评论状态分类的计数。
关键要点
- 参数 $post_id 可选,默认为 0,表示获取整个站点的评论统计;指定文章 ID 则仅统计该文章的评论。
- 返回一个整数数组,键包括 'approved'、'awaiting_moderation'、'spam'、'trash'、'post-trashed'、'total_comments' 和 'all',分别对应不同状态的评论数量。
- 内部使用 get_comments() 函数结合状态参数进行查询,并计算总和。
代码示例
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,
'orderby' => 'none',
);
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 );
}
原文内容
Retrieves the total comment counts for the whole site or a single post.
Parameters
$post_idintoptional-
Restrict the comment counts to the given post. Default 0, which indicates that comment counts for the whole site will be retrieved.
Source
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,
'orderby' => 'none',
);
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 );
}
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |