WordPress教程

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

阿里云

如果想显示某篇文章或当前文章所有评论者名称列表,可以参考一下本文的方法。使用场景,比如在文章适当位置,显示当前已有:史珍香,秦寿生,焦厚根,朱逸群,夏建仁等发表了热情扬溢的评论,再加一个锚点链接,引导读者跳转到评论表单,也发个热情扬溢的评论。将代码添加到当前主题函数模板 functions.php 中:

  1.     function get_comment_authors_list( $id = 0, $sep = ', ' ) {
  2.     	$post_id = $id ? $id : get_the_ID();
  3.     	if ( $post_id ) {
  4.     		$comments = get_comments( array(
  5.     			'post_id' => $post_id,
  6.     			'status'  => 'approve',
  7.     			'type'    => 'comment',
  8.     		) );
  9.  
  10.     		$names = array();
  11.     		foreach ( $comments as $comment ) {
  12.     			$name = $comment->comment_author;
  13.     			if ( $comment->user_id ) {
  14.     				$user = get_userdata( $comment->user_id );
  15.     				$name = $user ? $user->display_name : $name;
  16.     			}
  17.  
  18.     			$arr = explode( ' ', trim( $name ) );
  19.     			if ( ! empty( $arr[0] ) && ! in_array( $arr[0], $names ) ) {
  20.     				$names[] = $arr[0];
  21.     			}
  22.     		}
  23.     		unset( $comments );
  24.  
  25.     		$sep = $sep ? $sep : ', ';
  26.     		return implode( $sep, $names );
  27.     	}
  28.     }
  29.  
  30.  
  31.     add_shortcode( 'comment_authors_list', 'comment_authors_list_shortcode' );
  32.  
  33.     function comment_authors_list_shortcode( $atts = array() ) {
  34.     	$atts = shortcode_atts( array(
  35.     		'post_id'  => 0,
  36.     		'list_sep' => '',
  37.     	), $atts );
  38.  
  39.     	return get_comment_authors_list( $atts['post_id'], $atts['list_sep'] );
  40.     }
也想出现在这里?联系我们
创客主机

使用方法:

一、调用 ID 为:123 文章的所有评论者名称,在模板中使用:

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

在文章添加短代码:

  1. [comment_authors_list post_id="123" /]

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

  1. <?php echo get_comment_authors_list(); ?>

在文章中添加短代码:
[comment_authors_list /]

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

已有 149 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!