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.
statusintComment status to limit results by. Defaults to approved comments.post_idintLimit results to those affiliated with a given post ID.orderstringHow to order retrieved comments. Default'ASC'.
Default:
array()
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. |
Skip to note 2 content
Codex
Example
In this example we will output a simple list of comment IDs and corresponding post IDs.
comment_ID." => ".$comment->comment_post_ID."n"; } ?>