Extending the Snippet
Extending the Snippet
The base version of the [user_role] shortcode displays the primary internal slug of the current user's role (e.g., "administrator"). Depending on your site’s requirements, you may want to display multiple roles or translate these slugs into user-friendly names.
Below are common modifications you can apply to the code in your functions.php file.
Displaying All User Roles
By default, most snippets only fetch the first role assigned to a user. If your site uses a plugin that assigns multiple roles to a single user, you can modify the function to return a comma-separated list.
Update your function logic to:
function wp_show_user_role_multiple() {
$user = wp_get_current_user();
if ( ! empty( $user->roles ) && is_array( $user->roles ) ) {
// Joins all roles into a single string separated by commas
return implode( ', ', $user->roles );
}
return '';
}
add_shortcode( 'user_role', 'wp_show_user_role_multiple' );
Localizing or Renaming Roles
Internal WordPress slugs are always lowercase (e.g., editor, author). If you want to display "Site Manager" instead of "editor," or if you need to translate roles for a multi-lingual site, you can use a mapping array.
Example with custom labels:
function wp_show_user_role_localized() {
$user = wp_get_current_user();
if ( empty( $user->roles ) ) {
return '';
}
$role_slug = $user->roles[0];
// Define your user-friendly names here
$role_names = [
'administrator' => 'Site Admin',
'editor' => 'Content Manager',
'author' => 'Contributor',
'subscriber' => 'Member'
];
// Return the custom name if it exists, otherwise return the slug
return isset( $role_names[$role_slug] ) ? $role_names[$role_slug] : ucfirst($role_slug);
}
add_shortcode( 'user_role', 'wp_show_user_role_localized' );
Using WordPress Translated Labels
If you want to use the official labels defined in your WordPress settings (which respect your site's language files), you can use the global $wp_roles object to fetch the translated display name.
Example using system labels:
function wp_show_user_role_system_label() {
$user = wp_get_current_user();
if ( empty( $user->roles ) ) {
return '';
}
global $wp_roles;
$role_slug = $user->roles[0];
// Fetch the translated name from the WordPress roles global
return translate_user_role( $wp_roles->role_names[$role_slug] );
}
add_shortcode( 'user_role', 'wp_show_user_role_system_label' );
Usage in Templates
While the shortcode is designed for the WordPress Editor, you can also call these functions directly in your PHP theme files if needed:
// Display the role inside a template file
echo 'Current Role: ' . do_shortcode('[user_role]');