Here’s a simple code snippet that will help you check user roles on your WordPress site: simply copy the snippet given below in this post and add it to your child theme’s functions.php file or use a plugin like code snippets . Once activated, this code will check the user role .
function ts_check_user_role_display_message() {
// Check if the user is an administrator
if (current_user_can('administrator')) {
echo '<p>Welcome, Administrator! You have full access to the site.</p>';
}
// Check if the user is an editor
elseif (current_user_can('editor')) {
echo '<p>Welcome, Editor! You can manage and publish content.</p>';
}
// Check if the user is an author
elseif (current_user_can('author')) {
echo '<p>Welcome, Author! You can write and publish your own posts.</p>';
}
// Check if the user is a contributor
elseif (current_user_can('contributor')) {
echo '<p>Welcome, Contributor! You can write posts, but an editor must approve them.</p>';
}
// Check if the user is a subscriber
elseif (current_user_can('subscriber')) {
echo '<p>Welcome, Subscriber! You can manage your profile and comment on posts.</p>';
}
// For any other roles
else {
echo '<p>Welcome, guest! You have limited access.</p>';
}
}
// Hook the function to wp_head to display the message on the frontend
add_action('wp_head', 'ts_check_user_role_display_message');