I’m trying to add the user role once a user is logged in on wordpress and have the user role be in the body class=””
function my_class_names($classes) {
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
if ( is_user_logged_in() ) {
$classes[] = $user_role;
}
return $classes;
}
add_filter('body_class','my_class_names');
I’m not a php guy already tried research and i found how to get the user role, and another post was how to add body class and i’m have trouble how to get them both to work. I hope someone can help me out with this spent more than 2hrs trying to figure this out by myself 🙁
In my Case this code works perfectly by adding user role class to body class 🙂
Simply copy the code to function.php and paste it in a perfect place 😉
You can change your function to this
Then, change your body tag like this
If the user isn’t logged in, it will not add anything.
Or you can also add one more function (from the codex)
That will work.
WordPress 5.8 Answer:
You can easily add the current user’s role as a class to the body tag by adding the following code to your functions.php file in your theme.
Explanation of what this code does
It retrieves the roles that this user is a part of, and adds each one to the body class. And since WordPress supports assigning multiple roles to a user, this function will print out all roles a user is a part of. Each class will be prefixed with
role-
, so a user with the Editor role would outputrole-editor
to the body.The
add_filter( 'body_class', 'add_user_role_to_body_classes', 100 );
line adds the user role class(es) to the body tag on the front-end.The
add_filter( 'admin_body_class', 'add_user_role_to_body_classes', 100 );
line adds the user role class(es) to the body tag on the back-end (admin side of WordPress).You can add to the front or to the backend like so;
Similarly, if you wanted to add the user-id to the body class in the backend, you’d use: