显示WordPress 某个文章所有评论者名称

WordPress5542阅读模式

如果想显示某篇文章或当前文章所有评论者名称列表,可以参考一下本文的方法。

使用场景,比如在文章适当位置,显示当前已有:史珍香,秦寿生,焦厚根,朱逸群,夏建仁等发表了热情扬溢的评论,再加一个锚点链接,引导读者跳转到评论表单,也发个热情扬溢的评论。

显示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'] );
}

使用方法:

一、调用ID为:123文章的所有评论者名称

在模板中使用:

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

在文章添加短代码:

[comment_authors_list post_id="123" /]

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

在模板中使用

<?php echo get_comment_authors_list(); ?>

在文章中添加短代码:

[comment_authors_list /]

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
评论  5  访客  4  作者  1
    • maqingxi
      maqingxi 5

      在文章底部加个评论墙,还是挺能吸引读者去留言的。

      • Lvtu
        Lvtu 1

        把名称扩展为头像会不会更美观些 :razz:

          • 知更鸟
            知更鸟

            @ Lvtu 是的,你的头像目前就在侧边栏中有显示

              • Lvtu
                Lvtu 1

                @ 知更鸟 看到了,大神,为啥不把头像的教程也放上呢? :cool:

                • Lvtu
                  Lvtu 1

                  @ 知更鸟 貌似上面的代码还有一个问题,就是会把回复的博主名称也会显示出来?? :oops:

            匿名

            发表评论

            匿名网友
            :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

            拖动滑块以完成验证