当前浏览:首页 / WordPress函数 / get_comments()

get_comments( string|array $args = '' )

检索评论列表

comment 评论more...


描述

评论列表可以是整个博客的评论列表,也可以是单个文章的评论列表。


参数

$args

(string|array) (可选) 参数的数组或字符串,有关可接受参数的信息,请参阅WP_Comment_Query::__construct()

默认值: ''


返回

(WP_Comment[]|int[]|int) 评论列表或找到的评论数(如果$count参数为true)。



源码

查看源码 官方文档


更新日志

版本描述
2.7.0开始引入

使用示例

  • 示例1

    显示文章的评论数

    $args = array(
    	'post_id' => 1,   // Use post_id, not post_ID
            'count'   => true // Return only the count
    );
    $comments_count = get_comments( $args );
    echo $comments_count;
    
  • 示例2

    获取过去4周的评论

    $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
    }
    
  • 示例3

    实例

    $comments = get_comments( array( 'post_id' => 15 ) );
    
    foreach ( $comments as $comment ) :
    	echo $comment->comment_author;
    endforeach;
    
  • 示例4

    显示最后5条未经批准的评论

    $args = array(
    	'status'  => 'hold',
    	'number'  => '5',
    	'post_id' => 1, // use post_id, not post_ID
    );
    $comments = get_comments( $args );
    
    foreach ( $comments as $comment ) :
    	echo $comment->comment_author . '<br />' . $comment->comment_content;
    endforeach;
    
  • 示例5

    显示某用户的评论数

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

    显示某用户的评论

    <?php
    $args = array(
    	'user_id' => 1, // use user_id
    );
    $comments = get_comments( $args );
    
    foreach ( $comments as $comment ) :
    	echo $comment->comment_author . '<br />' . $comment->comment_content;
    endforeach;
    
  • 示例7

    获取两种文章类型的所有评论:

    $paged = get_query_var( 'page' ) ? get_query_var( 'page' ) : 1;
    $args  = array(
    	'number'    => 5,
    	'post_type' => array( 'property', 'page' ),
        'paged' => $paged,
        'parent' => 0,
    );
    $comments = get_comments($args);
    
  • 示例8

    获取父评论的子评论

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

    或者可以使用get_children()

    $comment->get_children()