在WordPress评论上显示用户角色标签图文教程

如果你想给那些在你的文章中具有较高角色的用户的评论更多的权重,你可能想在WordPress的评论中添加一个用户角色标签,让其他用户知道这些评论的作者的角色。但是许多WordPress主题还没有这个功能,所以来自注册用户、作者、甚至编辑的评论被显示出来,几乎看起来像一个未注册的用户。许多主题可能会突出显示文章作者的评论,然而,在评论上添加一个用户角色标签,可能会给它带来更多的意义。在本教程中,搬主题将向你介绍如何在WordPress的评论功能中添加用户角色标签的设置图文教程。

在WordPress评论上添加用户角色标签

在你开始在你的WordPress评论功能上添加用户角色标签之前,你可能想备份你的网站并使用一个子主题,以避免破坏父主题或在你更新主题时丢失你的改动,因为这个教程需要你在主题的 functions.php 文件中添加一些自定义代码。另外,为了安全地在你的WordPress主题中添加自定义代码,你可以使用代码片段插件,因为它是一个更容易和更快的方式来添加自定义代码和管理它们。

第1步:显示评论作者的角色

首先只要在你的主题functions.php文件中添加以下代码,导航到外观→主题文件编辑器(如果你使用的是块状主题,你可以在工具菜单下找到主题文件编辑器),打开文件编辑器。

// Get comment author role 
function wpp_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 wpp_comment_author_role($author) { 
return $author .= $this->comment_user_role; 
} 
}
new WPP_Comment_Author_Role_Label;
endif;

一旦你把代码添加到编辑器中,点击更新文件按钮,保存更改。上面的代码是用来在你的评论功能中显示评论作者的角色标签。

然而,正如你在上图中看到的,角色标签的位置与评论作者的昵称一致,这可能会被误认为是他们的完整昵称。因此,我们需要对角色进行一些样式设计,使其看起来与昵称不同。

第2步:为角色标签添加一些样式

要改变评论作者角色的样式,你可能需要在你的主题自定义→附加CSS中添加以下CSS片段,你可以从WordPress仪表板的外观菜单中进入。如果你使用的是块状主题,请阅读这里,为该主题启用主题定制器。

// Get comment author role 
function wpp_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 wpp_comment_author_role($author) { 
return $author .= $this->comment_user_role; 
} 
}
new WPP_Comment_Author_Role_Label;
endif;

一旦你把代码放在那里,通过点击发布按钮保存更改。上面的CSS将为角色标签添加一个彩色背景,然后将其向上移动一点。标签的颜色会根据评论作者的角色而改变。

最后总结

许多WordPress主题仍然没有给评论者更多权重的功能,所以来自注册用户、作者、甚至编辑的评论被显示出来,几乎看起来像未注册的用户。然而,在评论中添加一个用户角色标签可能会给他们的评论带来更多的意义。本教程告诉你如何在WordPress的评论功能中添加用户角色标签。

千百度
© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容