2

I'm trying to add the body class of the current user role to both the frontend and the admin backend.

Why does admin_body_class not work for admin?

The comment to this question does not work: How to insert the current user's role into the body class in the admin backend

This works for the front end in the theme's functions.php file:

add_filter("body_class", function($classes) {
    global $current_user;
    foreach ($current_user->roles as $user_role) {
        $classes[] = "role-{$user_role}";
    }
    return $classes;
});

This does not work for the backend in the theme's functions.php file:

add_filter("admin_body_class", function($classes) {
  $user = wp_get_current_user();
  foreach ($user->roles as $user_role) {
    $classes .= " role-{$user_role}";
  }
  return $classes;
});
6
  • where is your code located? when does it run? When this runs is significant it can't be put anywhere.
    – Tom J Nowell
    Commented Apr 28, 2022 at 16:20
  • 1
    You have no priority param on your filter, so technically the admin_body_class filter could be fired again after yours, and your changes could be overwritten. I can't say if this is the case, but I'd try adding a high priority value.
    – vancoder
    Commented Apr 28, 2022 at 16:21
  • @vancoder Thanks! What priority would I use for admin? Commented Apr 28, 2022 at 16:44
  • @TomJNowell Thanks! They are in the theme's functions.php file. Commented Apr 28, 2022 at 16:44
  • 1
    Try a high priority first (eg 99) and see if it helps.
    – vancoder
    Commented Apr 28, 2022 at 16:52

1 Answer 1

2

This works for the admin backend; I needed to restructure the filter to be able to add a priority:

function add_admin_body_class($classes) {
$user = wp_get_current_user();
foreach ($user->roles as $user_role) {
    $classes .= " role-{$user_role}";
  }
  return $classes;
}
add_filter("admin_body_class", "add_admin_body_class", 9999);
1
  • 1
    Actually you could have just added the priority at the end of your original anonymous function: }, 9999 );
    – vancoder
    Commented Apr 28, 2022 at 18:43

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.