WordPress 评论显示用户角色

WordPress3381阅读模式

通过本文的方法,可以在WordPress每条评论显示注册用户角色标签。

代码一,自动在评论者名称后面添加

代码添加到当前主题函数模板 functions.php 中:

if ( ! class_exists( 'ZM_Comment_Author_Role_Label' ) ) :
class ZM_Comment_Author_Role_Label {
	public function __construct() {
		add_filter( 'get_comment_author', array( $this, 'zm_get_comment_author_role' ), 10, 3 );
		add_filter( 'get_comment_author_link', array( $this, 'zm_comment_author_role' ) );
	}

	// 获取评论角色
	function zm_get_comment_author_role( $author, $comment_id, $comment ) { 
		$authoremail = get_comment_author_email( $comment); 
		// 检查用户是否注册
		if (email_exists($authoremail)) {
			$commet_user_role = get_user_by( 'email', $authoremail );
			$comment_user_role = $commet_user_role->roles[0];
			// 输出HTML
			$this->comment_user_role = '<span class="comment-author-label comment-author-label-' . $comment_user_role . '">' . ucfirst( $comment_user_role ) . '</span>';
		} else {
			$this->comment_user_role = '';
	}
		return $author;
	}

	// 显示评论角色
	function zm_comment_author_role( $author ) {
		return $author .= $this->comment_user_role;
	}
}
new ZM_Comment_Author_Role_Label;
endif;

之后,会在每条评论用户名称后面显示其注册角色。

代码二、自定义显示位置

代码添加到当前主题函数模板 functions.php 中:

function zm_get_comment_author_role() {
	global $author, $comment_id, $comment;
	$authoremail = get_comment_author_email( $comment);
	// 检查用户是否注册
	if (email_exists($authoremail)) {
		$commet_user_role = get_user_by( 'email', $authoremail );
		$comment_user_role = $commet_user_role->roles[0];
		// 输出HTML
		$comment_user_role = '<span class="comment-author-label comment-author-label-' . $comment_user_role . '">' . ucfirst( $comment_user_role ) . '</span>';
	} else {
		$comment_user_role = '';
	}
	echo $comment_user_role;
}

在评论模板适当位置添加:

<?php zm_get_comment_author_role(); ?>

最后,添加相应的CSS样式。

展开收缩
.comment-author-label {
	padding: 5px;
	font-size: 14px;
	border-radius: 3px;
}

.comment-author-label-editor {
	background-color: #efefef;
}

.comment-author-label-author {
	background-color: #faeeee;
}

.comment-author-label-contributor {
	background-color: #f0faee;
}

.comment-author-label-subscriber {
	background-color: #eef5fa;
}

.comment-author-label-administrator {
	background-color: #fde9ff;
}

另一段更简单的代码:

<?php
	$user_id = get_comment( get_comment_ID() )->user_id;
	if ( $user_id ){
		$user_info = get_userdata( $user_id );
		echo implode( ', ', $user_info->roles ) ;
	}
?>

直接添加到评论模板适当位置。

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

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
评论  3  访客  3
    • 轨魅网
      轨魅网 0

      :cool: 非常酷

      • 轨魅网
        轨魅网 3

        大写的牛逼,原来还可以这样 :mrgreen:

        • 微誓言
          微誓言 1

          这个可以用起来,很适用,权限分明

        匿名

        发表评论

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

        拖动滑块以完成验证