0

I am trying to load a custom styles sheet but only for administrators

My code works fine by itself:

function admin_style() {
  wp_enqueue_style('admin-styles', get_template_directory_uri().'/admin.css');
}
add_action('admin_enqueue_scripts', 'admin_style');

However, when I try to create a conditional based on the role, it can not get it to fire:

function role_exists( $role ) {
  if( ! empty( $role ) ) {
    return $GLOBALS['wp_roles']->administrator( $role );
  }
  return false;
}

function admin_style() {
  wp_enqueue_style('admin-styles', get_template_directory_uri().'/admin.css');
}

if( role_exists( 'administrator' ) ) {
  return
  add_action('admin_enqueue_scripts', 'admin_style');
}

1 Answer 1

1

This is what I use, tested and works...

function wpse_admin_styles(){
    $user = wp_get_current_user();

    if( !empty($user) && count(array_intersect(["administrator"], (array) $user->roles ))) {
        wp_enqueue_style(
            'admin_css', 
            get_stylesheet_directory_uri() . '/css/admin-styles.css', array(), filemtime( get_stylesheet_directory() . '/css/admin-styles.css') 
        );
    }
}

add_action('admin_enqueue_scripts', 'wpse_admin_styles');
1
  • Worked perfectly, thank you!
    – Eric D.
    Commented May 23, 2019 at 20:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.