Translating Role Names
Customizing and Translating Role Names
By default, WordPress stores user roles as lowercase "slugs" (e.g., administrator, editor, shop_manager). If you want the [user_role] shortcode to display a more user-friendly name or a translated version, you can modify the code snippet in your functions.php file.
Using Manual Mapping
If you want to provide specific labels for your roles, you can use an associative array to map the raw slugs to display names.
Update your function logic to include a mapping array:
function get_custom_user_role_name() {
$current_user = wp_get_current_user();
if ( ! ( $current_user instanceof WP_User ) || empty( $current_user->roles ) ) {
return '';
}
// Get the first role slug
$role_slug = $current_user->roles[0];
// Define your custom labels here
$role_labels = [
'administrator' => 'Site Admin',
'editor' => 'Content Manager',
'author' => 'Contributor',
'subscriber' => 'Member'
];
// Return the custom label if it exists, otherwise return the slug capitalized
return isset($role_labels[$role_slug]) ? $role_labels[$role_slug] : ucfirst($role_slug);
}
Supporting Internationalization (i18n)
If your site is multilingual or you want to use the default WordPress translations for standard roles, you should use the wp_roles() global object. This ensures that the role name matches the language set in the WordPress settings.
Replace the return logic in your app.php snippet with the following:
function get_translated_user_role() {
$current_user = wp_get_current_user();
if ( empty( $current_user->roles ) ) {
return '';
}
$role_slug = $current_user->roles[0];
$wp_roles = wp_roles();
// Fetch the translated display name from the global WordPress roles
return translate_user_role( $wp_roles->role_names[$role_slug] );
}
Practical Example: Prepend Text
You can also modify the shortcode output to include prefix text directly within the code:
// In your shortcode callback function
$role = get_translated_user_role();
return '<span class="user-role-display">Your Access Level: ' . $role . '</span>';
Usage Tips
- Fallback: Always ensure your code handles cases where a user might not have a role (e.g., logged-out users or specific custom setups).
- CSS Styling: Wrap the output in a
<span>with a specific class (as shown above) to style the role name via your theme's CSS.