This guide explains how to easily add the current user role as a class to the WordPress body in the frontend and the WP admin, this would look like so class="administrator user-id-1". This is particularly useful if you want to add a style for a specific user or user role group. It can also be used to hide elements quickly although we don’t recommend this method for hiding elements with CSS.

The function below can be used in the theme functions or better in an MU plugin, if you are using a Multisite then we highly recommend that you place in an MU plugin.

/**
 * Add User Role Class to Body
 * Referenced code from http://www.studiok40.com/
 */
function print_user_classes() {
    if ( is_user_logged_in() ) {
        add_filter('body_class','class_to_body');
        add_filter('admin_body_class', 'class_to_body_admin');
    }
}
add_action('init', 'print_user_classes');

/// Add user role class to front-end body tag
function class_to_body($classes) {
    global $current_user;
    $user_role = array_shift($current_user->roles);
    $classes[] = $user_role.' ';
    return $classes;
}

/// Add user role class and user id to front-end body tag

// add 'class-name' to the $classes array
function class_to_body_admin($classes) {
    global $current_user;
    $user_role = array_shift($current_user->roles);
    /* Adds the user id to the admin body class array */
    $user_ID = $current_user->ID;
    $classes = $user_role.' '.'user-id-'.$user_ID ;
    return $classes;
    return 'user-id-'.$user_ID;
}

If you need help adding this function to your site please leave a comment below, need to do something more complex? Then get in touch with us, our One-Off WordPress Support is as little as $20.