Conditional Extensions
Conditional Extensions
While the default [user_role] shortcode displays the current user's role globally, you may want to restrict its visibility or modify the output based on specific logic. Below are several ways to extend the snippet in your functions.php file to handle conditional requirements.
Only Show for Logged-In Users
By default, the shortcode might return an empty string or error for guests. You can wrap the logic to ensure it only executes for authenticated users.
function wp_show_user_role_conditional() {
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$roles = ( array ) $user->roles;
return esc_html( reset( $roles ) );
}
return 'Guest'; // Optional: Return custom text for logged-out users
}
Restricting Display to Specific Roles
If you only want the shortcode to output a value if the user has a certain level of authority (e.g., "Editor" or "Administrator"), use current_user_can().
function wp_show_user_role_restricted() {
// Only show the role if the user is at least an Editor
if ( current_user_can( 'edit_others_posts' ) ) {
$user = wp_get_current_user();
return esc_html( reset( $user->roles ) );
}
return ''; // Return nothing for subscribers or guests
}
Excluding Specific Roles
You may want to hide the role display for sensitive accounts like Administrators while showing it for everyone else.
function wp_show_user_role_exclude_admin() {
$user = wp_get_current_user();
$roles = ( array ) $user->roles;
$current_role = reset( $roles );
// Do not show if the user is an administrator
if ( $current_role === 'administrator' ) {
return '';
}
return esc_html( $current_role );
}
Dynamic Styling via CSS Classes
To change the appearance of the role based on what the role is, you can wrap the output in a span with a dynamic class.
function wp_show_user_role_styled() {
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$role = reset( $user->roles );
// Returns <span class="role-editor">editor</span>
return '<span class="role-' . esc_attr( $role ) . '">' . esc_html( $role ) . '</span>';
}
}
Usage with Shortcode Attributes
You can modify the function to accept attributes, allowing you to choose whether to capitalize the role directly in the WordPress editor:
[user_role format="uppercase"]
function wp_show_user_role_advanced( $atts ) {
$a = shortcode_atts( array(
'format' => 'default',
), $atts );
$user = wp_get_current_user();
$role = reset( $user->roles );
if ( $a['format'] === 'uppercase' ) {
return esc_html( strtoupper( $role ) );
}
return esc_html( ucfirst( $role ) );
}