Custom CSS In Admin Only For Certain Roles

I’m looking to apply custom CSS in the admin only for a certain user role, “Contributor” to be exact.

Everything I try either seems to have no effect, or produces a 500 error.

What I’ve tried has in the main been loosely based around this:

add_action('admin_head', 'custom_admin_css');

function custom_admin_css( ){

global $user;

if (isset($user->roles)  && is_array( $user->roles ) ) {

    if( $user->roles[0] == 'administrator' ) {
        //Do something
    } elseif ( $user->roles[0] == 'editor' ) {
        //Do something
    } elseif ( $user->roles[0] == 'contributor') {
        echo '<style> CSS </style>';
    } else {
        //Do something
    }
}
}

2 Answers
2

Upon request I will write an answer using a function from a suggested answer for the similar question: How to target with css, admin elements according to user role level?.

This function will output classes to the body element for all roles of the current user in the form role-XXXXX

function wpa66834_role_admin_body_class( $classes ) {
    global $current_user;
    foreach( $current_user->roles as $role )
        $classes .= ' role-' . $role;
    return trim( $classes );
}
add_filter( 'admin_body_class', 'wpa66834_role_admin_body_class' );

Now the roles can be targeted with css rules like:

#targetElement { 
    display: none; 
}
.role-editor #targetElement { 
    display: visible; 
}

These CSS rules don’t have to be output conditionally. They can be placed for example in any CSS file which is included via admin_enqueue_scripts action:

function wp245372_admin_enqueue_scripts() {
    wp_enqueue_style( 'my-admin-css', 'path/to/file.css', array(), 0.1);
}
add_action( 'admin_enqueue_scripts', 'wp245372_admin_enqueue_scripts' );

Leave a Comment