WordPress
主题插件美化教程

WordPress教程:WordPress 评论显示用户角色

WordPress教程:WordPress 评论显示用户角色
通过本文的方法,可以在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样式。
另一段更简单的代码:

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

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

 收藏 (0) 打赏

您可以选择一种方式赞助本站

支付宝扫一扫赞助

微信钱包扫描赞助

未经允许不得转载:彩红网 » WordPress教程:WordPress 评论显示用户角色
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录   注册

切换注册

登录

忘记密码 ?

   
切换登录

注册

我们将发送一封验证邮件至你的邮箱, 请正确填写以完成账号注册和激活