How to add a user role label next to comments in WordPress

Blog post comments are a fantastic way to interact with your readers. But your comments and those of your editorial team can be given additional weight by identifying as “official” responses from your website. One way to do this is to label those comments with the WordPress user role – “Admin”, “Editor”, “Author” and so on.

Use the following steps to add a user role label next to comments in WordPress.

Adding the role label requires us to edit the WordPress theme’s functions.php file, which we can do using cPanel File Manager.

Log into the HostPapa dashboard and visit My cPanel. Head to Files > cPanel File Manager to view the files and folders stored on your server.

cPanel

Navigate to your WordPress folder then enter the wp-content > themes folder. Open the folder for your current theme, then select functions.php and click Edit in the command bar.

cPanel File Manager

Scroll to the bottom of the page, and enter the following code:

/**
* Add User Role to Comments.
*/
if ( ! class_exists( 'Comment_Author_Role_Label' ) ) :
class Comment_Author_Role_Label {
public function __construct() {
add_filter( 'get_comment_author', array( $this, 'get_comment_author_role' ), 10, 3 );
add_filter( 'get_comment_author_link', array( $this, 'comment_author_role' ) );
}
function 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];
$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 comment_author_role($author) {
return $author .= $this->comment_user_role;
}
}
new Comment_Author_Role_Label;
endif;

Save the file and close cPanel File Manager.

Now visit your site’s front end and review comments you’ve made on posts. You should see your user role displayed next to your name.

Comment form

If you notice any problems or if you need any help, please open a new support ticket from your HostPapa Dashboard. More details on how to open a support ticket can be found here.

Was this article helpful?

  • Was this article helpful ?

  • yes   no

Related Articles

Leave A Comment?