WordPress函数:get_comments 强大的评论查询功能

追格官方小助手/ 2022年12月22日/ WordPress/ 浏览 1630

WordPress中绝大多数函数的命名都是有规律的。文章和评论又是 WordPress 系统中的重点内容。


所以,有 WP_Query 就有 WP_Comment_Query,有 get_posts 就有 get_comments,有 pre_get_posts 就有 pre_get_comments……


今天学习的函数是 get_comments,先看一下源码:


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


所以,get_comments 和 WP_Comments_Query 几乎是无差别的。


get_comments 的参数众多,暂且不论。今天先看几个简单的例子,体会一下:


$comments = get_comments( array( 'post_id' => 15 ) );

foreach ( $comments as $comment ) :
	echo $comment->comment_author;
endforeach;


查询文章ID为15的所有评论。


$args = array(
	'user_id' => 1,   // Use user_id.
	'count'   => true // Return only the count.
);
$comments_count = get_comments( $args );

echo $comments_count;


查询用户ID为1的用户总共发布了多少条评论。


$args = array(
	'date_query' => array(
		'after' => '4 weeks ago',
		'before' => 'tomorrow',
		'inclusive' => true,
	),
);

$comments = get_comments( $args );
foreach ( $comments as $comment ) {
	// Output comments etc here
}


查询,4周前到昨天发布的评论。


$args           = array(
    'parent'       => $comment->comment_ID, //Comment ID '64'
    'hierarchical' => true,
    'status'       => 'approve',
);
$child_comments = get_comments( $args );


查询指定评论的回复信息(也是评论)。


发表评论

暂无评论,抢个沙发...

客服 工单