WordPress如何获得整站或某篇文章的评论数(含一级或某个状态评论数)

WordPress国产主题推荐

我们平时用得比较多的就是获得整个WordPress站点的评论数,或者某篇文章的评论数,但是如果只想获得一级评论数,或某个状态的评论数,那么应该怎么获取呢?下面boke112百科就跟大家介绍3个获取WordPress评论数的函数。

一、get_comments_number()函数

get_comments_number(int|WP_Post $post):string|int

其中参数一般是文章ID,不填写则默认为当前文章。

这个函数返回当前文章或指定文章已批准的评论数。

二、get_comment_count()函数

get_comment_count( int $post_id ): int[]

其中$post_id是文章ID,不填写则默认为整个站点。

这个函数返回指定文章或整个WordPress网站的某个状态评论数。

比如获取整个网站已批准的评论数代码如下:

$comment_count=get_comment_count();
$comment_count['approved']

其中approved表示已经批准的评论数,我们还可以将其修改为:

  • approved:已经批准的评论数
  • awaiting_moderation:待审的评论数
  • spam:垃圾评论数
  • trash:回收站中的评论数
  • post-trashed:回收站中的文章的评论数
  • total_comments:待审+已批准+垃圾的评论数
  • all:待审和已批准的评论数

三、get_comments()函数

get_comments( string|array $args = ” ): WP_Comment[]|int[]|int

返回指定文章或整个WordPress网站的评论列表。

其中参数可默认为空,也可以根据实际需要填写想要的查询条件,具体如下:

$args = array(
'author_email' => '',
'author__in' => '',
'author__not_in' => '',
'include_unapproved' => '',
'fields' => '',
'ID' => '',
'comment__in' => '',
'comment__not_in' => '',
'karma' => '',
'number' => '',
'offset' => '',
'orderby' => '',
'order' => 'DESC',
'parent' => '',
'post_author__in' => '',
'post_author__not_in' => '',
'post_ID' => '', // ignored (use post_id instead)
'post_id' => 0,
'post__in' => '',
'post__not_in' => '',
'post_author' => '',
'post_name' => '',
'post_parent' => '',
'post_status' => '',
'post_type' => '',
'status' => 'all',// 可选hold、approve、all、spam、trash等
'type' => '',
'type__in' => '',
'type__not_in' => '',
'user_id' => '',
'search' => '',
'count' => false,
'meta_key' => '',
'meta_value' => '',
'meta_query' => '',
'date_query' => null, // See WP_Date_Query
);

比如我们想要获得某篇文章已批准的一级评论数,可使用以下代码:

// 获取指定文章一级评论数量
$args = array(
'post_id' => get_the_ID(),
'status' => 'approve',
'parent' => 0,
'count' => true
);
echo $comment_count = get_comments($args);

其中第3行代码中的get_the_ID()也可以改为$post->ID,

比如我们想要获得整个WordPress网站已批准的一级评论数,可使用以下代码:

// 获取整站一级评论数量
$args = array(
'status' => 'approve',
'parent' => 0,
'count' => true
);
echo $comment_count = get_comments($args);
文章创作不易,期待您的评分

本文地址:https://boke112.com/article/12285.html

版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu