最近访客
百度未收录

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

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

将以下代码添加到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 /]

温馨提示: 本文最后更新于2022/10/20 03:39:55。若文章内容或图片失效,请 留言联系站长反馈!
!
也想出现在这里? 联系我们
创意广告
© 版权声明
THE END
点赞0赞赏 分享
评论 抢沙发

请登录后发表评论

    请登录后查看评论内容