函数文档

get_comments()

💡 云策文档标注

概述

get_comments() 是 WordPress 中用于检索评论列表的核心函数,支持通过参数灵活筛选评论,可返回评论数组或数量。该函数基于 WP_Comment_Query 类实现,适用于全站或单个文章的评论查询。

关键要点

  • 函数功能:检索评论列表,可指定参数进行过滤,如按文章 ID、用户 ID、状态等。
  • 参数说明:$args 参数为字符串或数组,具体选项参考 WP_Comment_Query::__construct(),默认值为空字符串。
  • 返回值:返回 WP_Comment[] 数组、int[] 数组或 int 类型,取决于 $count 参数是否设置为 true。
  • 内部实现:函数内部实例化 WP_Comment_Query 并调用其 query() 方法执行查询。
  • 相关用途:广泛用于评论管理、数据导出、仪表板显示等场景,如 wp_list_comments() 和 get_comment_count()。
  • 版本历史:自 WordPress 2.7.0 版本引入。

代码示例

// 获取文章评论数量示例
$args = array(
    'post_id' => 1,
    'count'   => true
);
$comments_count = get_comments( $args );
echo $comments_count;

// 获取最近4周评论示例
$args = array(
    'date_query' => array(
        'after' => '4 weeks ago',
        'before' => 'tomorrow',
        'inclusive' => true,
    ),
);
$comments = get_comments( $args );
foreach ( $comments as $comment ) {
    // 输出评论内容
}

// 获取特定文章评论示例
$comments = get_comments( array( 'post_id' => 15 ) );
foreach ( $comments as $comment ) :
    echo $comment->comment_author;
endforeach;

注意事项

  • 参数命名:使用 'post_id' 而非 'post_ID',确保参数键名正确。
  • 返回值处理:当 $count 为 true 时,返回整数类型;否则返回评论对象数组。
  • 性能考虑:对于大量评论查询,建议合理设置参数如 'number' 以限制返回数量。

📄 原文内容

Retrieves a list of comments.

Description

The comment list can be for the blog as a whole or for an individual post.

Parameters

$argsstring|arrayoptional
Array or string of arguments. See WP_Comment_Query::__construct() for information on accepted arguments. Default empty string.

Return

WP_Comment[]|int[]|int List of comments or number of found comments if $count argument is true.

Source

function get_comments( $args = '' ) {
	$query = new WP_Comment_Query();
	return $query->query( $args );
}

Changelog

Version Description
2.7.0 Introduced.

User Contributed Notes