There are two code snippets required here. Be sure to grab the CSS code snippet as well.
Add Body Class For All User Roles to WordPress
This code snippet adds body classes for user roles to WordPress using the body_class filter. You don’t need to concern yourself with the geeky details, but I wanted to share them for documentation purposes.
add_filter( 'body_class', 'body_class_user_role' );
function body_class_user_role( $classes ) {
if( is_user_logged_in() ) {
$user_role = wp_get_current_user()->roles;
$classes[] = 'user-role-' . $user_role[0];
}
return $classes;
}Target the Subscriber Role
This code snippet targets the ‘Subscriber’ role and hides any content with the ‘hidecontent’ CSS class assigned to it. To target different roles, replace ‘subscriber’ with the role of your choice.
The CSS class, which in this case is ‘hidecontent,’ can be written any way you want (ex. hideme, hidethis, etc.).
.logged-in.user-role-subscriber .hidecontent {
display: none;
}Target Multiple Roles
This is a real-world example of a code snippet I use to hide the Vendor Dashboard menu item from the Customer, Subscriber, Editor, and Autor roles when implementing the WooCommerce Product Vendors plugin.
To finish the job, I assigned the ‘hidecontent’ CSS class to the ‘Vendor Dashboard’ menu item.
.logged-in.user-role-customer .hidecontent,
.logged-in.user-role-subscriber .hidecontent,
.logged-in.user-role-editor .hidecontent,
.logged-in.user-role-author .hidecontent
{
display: none;
}Example Use Cases
- Hide buttons by adding the ‘hidecontent’ CSS class to the Elementor Button widget.
- Hide MyListing Single Listing Blocks by adding the ‘hidecontent’ CSS class to the block within the Listing Type configuration.
- Hide Menu items by exposing the CSS attribute setting in the WordPress menus and adding the ‘hidecontent’ CSS class to the desired menu items.
