Show Your Role in the Toolbar
Adds the current user's role next to their name in the admin toolbar ("Howdy, Sam (Editor)"), helpful when testing with several accounts.
Opens WPIDE on
Code
add_action( 'admin_bar_menu', function ( $bar ) {
$node = $bar->get_node( 'my-account' );
if ( ! $node || ! is_user_logged_in() ) {
return;
}
$names = array();
foreach ( (array) wp_get_current_user()->roles as $role ) {
$names[] = isset( wp_roles()->role_names[ $role ] ) ? translate_user_role( wp_roles()->role_names[ $role ] ) : $role;
}
if ( $names ) {
$node->title = preg_replace( '/(<span class="display-name">)(.*?)(<\/span>)/', '$1$2 (' . esc_html( implode( ', ', $names ) ) . ')$3', $node->title, 1 );
$bar->add_node( (array) $node );
}
}, 999 );
Notes
Shows all roles when a user has more than one.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.