Add User Role to Body Class in WordPress Admin

Here is a way to add a class based on the user role in the WordPress admin. Add the following code to your theme’s functions.php file:

add_filter('admin_body_class', function($classes) {
    global $current_user;
 
    if(is_array($current_user->roles)) {
        foreach($current_user->roles as $role) {
            $classes .= "user-role-{$role} ";
        }
    }
 
    return rtrim($classes);
});

The result will look something like:

<body class="... user-role-administrator ...">

This uses the body_class filter. Learn more in WordPress Hooks Explained.

Discussion
[  0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!