通过本文的方法,可以在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 ) ;
}
?>直接添加到评论模板适当位置。
本站文章大部分为原创,用于个人学习记录,可能对您有所帮助,仅供参考!

我的微信
微信号已复制
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!






1F
2F
大写的牛逼,原来还可以这样
3F
这个可以用起来,很适用,权限分明