您是否在受欢迎的网站上看到那些鼓励用户发推文的精美报价框?这…
我们的一位读者问,是否可以在WordPress中的每个注释旁边突出显示用户角色?显示用户角色标签可以使注册用户在您网站上(尤其是作者,编辑和管理员)所发表的评论更为重要。在本文中,我们将向您展示如何在WordPress注释旁边轻松添加用户角色标签。

为什么在WordPress中的评论作者姓名旁边显示用户角色标签?
如果允许用户在您的网站上注册或运行多作者WordPress网站,则用户标签可以根据用户角色将用户介绍给彼此。
例如,具有编辑者用户角色的用户将在评论的名称旁边显示一个徽章,让其他用户知道此评论是由编辑者做出的。
它建立了用户信任,并增加了用户对您网站上评论的参与度。
许多WordPress主题仅强调帖子作者的评论。即使已注册用户或站点管理员发表了其他评论,它们也不会显示任何其他用户角色的标签。
话虽如此,让我们看一下如何轻松地在WordPress中的注释旁边添加用户角色标签。
在WordPress中的评论作者姓名旁边添加用户角色标签
本教程要求您将代码添加到WordPress主题文件中。如果您以前没有做过,请查看我们的指南,了解如何轻松地在WordPress中复制和粘贴代码。
您需要做的第一件事是将以下代码添加到主题的functions.php文件或特定于站点的插件中。
if
( !
class_exists
(
'WPB_Comment_Author_Role_Label'
) ) :
class
WPB_Comment_Author_Role_Label {
public
function
__construct() {
add_filter(
'get_comment_author'
,
array
(
$this
,
'wpb_get_comment_author_role'
), 10, 3 );
add_filter(
'get_comment_author_link'
,
array
(
$this
,
'wpb_comment_author_role'
) );
}
// Get comment author role
function
wpb_get_comment_author_role(
$author
,
$comment_id
,
$comment
) {
$authoremail
= get_comment_author_email(
$comment
);
// Check if user is registered
if
(email_exists(
$authoremail
)) {
$commet_user_role
= get_user_by(
'email'
,
$authoremail
);
$comment_user_role
=
$commet_user_role
->roles[0];
// HTML output to add next to comment author name
$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
;
}
// Display comment author
function
wpb_comment_author_role(
$author
) {
return
$author
.=
$this
->comment_user_role;
}
}
new
WPB_Comment_Author_Role_Label;
endif
;
上面的此功能代码与WordPress过滤器挂钩,该过滤器用于显示评论作者姓名以包括用户角色标签。
现在,您可以访问带有评论的任何帖子,以查看其运行情况。注册用户发表的评论将在评论作者名称旁边显示其用户角色。非注册用户发表的任何评论将仅显示评论作者姓名。
现在,我们已经添加了用户角色,现在该为它设置样式并使其看起来干净了。
在我们的代码中,我们为每个用户角色添加了一个CSS类,因此我们可以使用这些CSS类以不同的方式自定义每个用户徽章(即使用不同的颜色等)
您可以使用以下示例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
;
}
可以根据自己的喜好随意调整CSS。