Add User Role to Body Class

Share this resource

Share on facebook
Share on twitter
Share on linkedin
Share on email
Share on facebook
Submitted by: Donald McGuinn

Insert this code into your child theme functions.php file. Then, use the class selector below.

.role-administrator

.role-editor

.role-author

.role-subscriber

.role-customer

// ADD USER ROLE TO BODY CLASS
// ============================================================================= 
if ( is_user_logged_in() ) {
    add_filter('body_class','add_role_to_body');
    add_filter('admin_body_class','add_role_to_body');
}
function add_role_to_body($classes) {
    $current_user = new WP_User(get_current_user_id());
    $user_role = array_shift($current_user->roles);
    if (is_admin()) {
        $classes .= 'role-'. $user_role;
    } else {
        $classes[] = 'role-'. $user_role;
    }
    return $classes;
}