WordPress显示出某篇文章所有评论者的名称

一篇优质的文章,会使得大量的用户进行评论互动,当评论一多,就会让人看得眼花缭乱(有些还有分页功能)。这个时候,我们可以使用一段代码来显示某篇文章的所有评论者。 将以下代码添加到WordPress当前主题的函数模板functions.php里面 代码实现 function get_comment_authors_list...

一篇优质的文章,会使得大量的用户进行评论互动,当评论一多,就会让人看得眼花缭乱(有些还有分页功能)。这个时候,我们可以使用一段代码来显示某篇文章的所有评论者。

将以下代码添加到WordPress当前主题的函数模板functions.php里面

代码实现

function get_comment_authors_list( $id = 0, $sep = ', ' ) {
	$post_id = $id ? $id : get_the_ID();
	if ( $post_id ) {
		$comments = get_comments( array(
			'post_id' => $post_id,
			'status'  => 'approve',
			'type'    => 'comment',
		) );
 
		$names = array();
		foreach ( $comments as $comment ) {
			$name = $comment->comment_author;
			if ( $comment->user_id ) {
				$user = get_userdata( $comment->user_id );
				$name = $user ? $user->display_name : $name;
			}
 
			$arr = explode( ' ', trim( $name ) );
			if ( ! empty( $arr[0] ) && ! in_array( $arr[0], $names ) ) {
				$names[] = $arr[0];
			}
		}
		unset( $comments );
 
		$sep = $sep ? $sep : ', ';
		return implode( $sep, $names );
	}
}
 
 
add_shortcode( 'comment_authors_list', 'comment_authors_list_shortcode' );
 
function comment_authors_list_shortcode( $atts = array() ) {
	$atts = shortcode_atts( array(
		'post_id'  => 0,
		'list_sep' => '',
	), $atts );
 
	return get_comment_authors_list( $atts['post_id'], $atts['list_sep'] );
}

使用方法

1.查看文章ID为567,下面所有的评论者有哪些

就在你的模板中添加以下代码

<?php echo get_comment_authors_list('123'); ?>

这样就可以显示出所有参与评论的评论者

文章中添加短代码

[comment_authors_list post_id="123" /]

2.调用当前文章所有评论者名称,与上面类似只是去掉其中的文章ID,适合放在文章正文模板中。

就在你的模板中添加以下代码

<?php echo get_comment_authors_list(); ?>

在文章中添加短代码:

[comment_authors_list /]
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
豆包可以帮你高效完成AI问答、AI对话、提供软件相关教程以及解决生活中遇到的各种疑难杂症,还能帮助你进行AI写作、AI绘画等等,提高你的工作学习效率。
!
你也想出现在这里?立即 联系我们吧!
信息
个人中心
购物车
优惠劵
今日签到
搜索