Skip to content

Instantly share code, notes, and snippets.

@jancbeck
Last active January 15, 2022 19:34
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jancbeck/3178689 to your computer and use it in GitHub Desktop.
Save jancbeck/3178689 to your computer and use it in GitHub Desktop.
WordPress: Add user role class to body tag
<?php
// Add role class to body
function add_role_to_body($classes) {
foreach (wp_get_current_user()->roles as $user_role) {
$classes[] = 'role-'. $user_role;
}
return $classes;
});
add_filter('body_class','add_role_to_body');
add_filter('admin_body_class', 'add_role_to_body');
?>
@MarcyCapron
Copy link

@joanna-s thank you!!

@santiazpi
Copy link

santiazpi commented Nov 12, 2019

This works for serveral user roles per user....
`function add_role_to_body($classes) {

global $current_user;
foreach ($current_user->roles as $user_role)
	$classes[] = 'role-'. $user_role;

return $classes;

}
add_filter('body_class','add_role_to_body');
`

@tedw
Copy link

tedw commented Nov 14, 2019

Here’s @santiazpi’s code with the syntax highlighting fixed, plus refactored to use a function expression as the callback:

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

    return $classes;
});

FYI, here’s how to add role classes in the WP admin:

add_filter("admin_body_class", function($classes) {
  $user = wp_get_current_user();
  foreach ($user->roles as $user_role) {
    $classes .= " role-{$user_role}";
  }
  return $classes;
});

https://developer.wordpress.org/reference/hooks/admin_body_class/

@jancbeck
Copy link
Author

jancbeck commented Nov 15, 2019

Thanks @tedw I've updated the gist using your second function which seems to be compatible with the frontend theme as well.

@michaelignacio
Copy link

Agreed, I used the first snippet posted by @tedw and it works perfectly on the frontend. Don't really need the role as body classes on my WP Admin.

@michalprekop
Copy link

Thank you @tedw it works great!

@posgross
Copy link

HELLO
I am beginner! Pltease help!

I need the snippet, which will hide the button ADD LISTING for couple roles

Please help I don't understand

I download and install "Code Snippets"

For test I take the code from the first messages of this discussion

http://joxi.ru/Y2Lw477tMb1Rvm

I need make 2 snippets for two different roles

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment