函数文档

get_approved_comments()

💡 云策文档标注

概述

get_approved_comments() 函数用于检索指定文章的已批准评论。它基于 WP_Comment_Query 实现,支持通过参数自定义查询条件。

关键要点

  • 函数接受两个参数:必需的 $post_id(文章 ID)和可选的 $args(查询参数数组)。
  • 默认查询状态为已批准(status 默认为 1),并按升序(order 默认为 'ASC')返回评论。
  • 返回类型为 WP_Comment[]、int[] 或 int,具体取决于 $count 参数是否设置为 true。
  • 该函数在 WordPress 4.1.0 版本中重构,以利用 WP_Comment_Query 替代直接查询。

代码示例

// 示例:输出评论 ID 和对应文章 ID
$comments = get_approved_comments(123);
foreach ($comments as $comment) {
    echo $comment->comment_ID . " => " . $comment->comment_post_ID . "n";
}

📄 原文内容

Retrieves the approved comments for a post.

Parameters

$post_idintrequired
The ID of the post.
$argsarrayoptional
See WP_Comment_Query::__construct() for information on accepted arguments.

  • status int
    Comment status to limit results by. Defaults to approved comments.
  • post_id int
    Limit results to those affiliated with a given post ID.
  • order string
    How to order retrieved comments. Default 'ASC'.

Default:array()

Return

WP_Comment[]|int[]|int The approved comments, or number of comments if $count argument is true.

Source

function get_approved_comments( $post_id, $args = array() ) {
	if ( ! $post_id ) {
		return array();
	}

	$defaults    = array(
		'status'  => 1,
		'post_id' => $post_id,
		'order'   => 'ASC',
	);
	$parsed_args = wp_parse_args( $args, $defaults );

	$query = new WP_Comment_Query();
	return $query->query( $parsed_args );
}

Changelog

Version Description
4.1.0 Refactored to leverage WP_Comment_Query over a direct query.
2.0.0 Introduced.

User Contributed Notes