-
-
Save jancbeck/3178689 to your computer and use it in GitHub Desktop.
<?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'); | |
?> |
With WordPress, users can technically have more than one Role. It looks like this is only pulling in the "first" role. Is there a way to display ALL roles, each as a new class?
I am glad this came into somebodys mind :) Awesome way to hide and show certain areas of wordpress depending on the user roles. I am using Wordpress 4.7.3 right now and @bryanwillis ' code snippet is doing a great job adding the role class to the body tag. Coooooool! :) Thank you very much guys!
where to add this code guys?
I found this didn't play well with the theme I'm using (if it were up to me I'd make my own themes but i'm not the boss unfortunately..), hope this helps any one in my position :)
function add_role_to_body($classes) {
global $current_user;
$user_role = $current_user->roles;
return array_merge( $classes, array( $user_role[0] ) );
}
add_filter('body_class','add_role_to_body');
@joanna-s thank you!!
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');
`
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/
Thanks @tedw I've updated the gist using your second function which seems to be compatible with the frontend theme as well.
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.
Thank you @tedw it works great!
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
I need make 2 snippets for two different roles
I modified it so it also includes the user's id, and if this is placed in a functionality plugin, that it deals with the pluggability problem :