Disable WordPress Admin Bar for Specific User Roles
Custom Code Solution
Here's a code snippet that disables the WordPress admin bar for specific user roles. Add this to your theme's functions.php
file or in a site-specific plugin:
This code removes the admin bar for selected user roles:
function remove_admin_bar_for_roles() {
if (!is_user_logged_in()) {
return;
}
$user = wp_get_current_user();
$disabled_roles = array(
'subscriber',
'customer',
'contributor'
// Add more roles as needed
);
if (array_intersect($disabled_roles, $user->roles)) {
add_filter('show_admin_bar', '__return_false');
}
}
add_action('init', 'remove_admin_bar_for_roles');
Alternative version that enables the admin bar only for specific roles:
function show_admin_bar_for_specific_roles() {
if (!is_user_logged_in()) {
return;
}
$user = wp_get_current_user();
$enabled_roles = array(
'administrator',
'editor'
// Add more roles as needed
);
if (!array_intersect($enabled_roles, $user->roles)) {
add_filter('show_admin_bar', '__return_false');
}
}
add_action('init', 'show_admin_bar_for_specific_roles');
Code Placement Options
- Add to your theme's
functions.php
file
- Create a site-specific plugin
- Use a code snippets plugin like "Code Snippets"
Plugin Solutions
If you prefer a plugin solution, these options work well:
-
User Role Editor - Offers granular control over user roles and capabilities, including admin bar visibility
-
AdminBar - Simple plugin to control admin bar visibility per user role
-
Code Snippets - For safely adding custom code without editing theme files
Additional Notes
- The code is compatible with WordPress 5.0 and above
- Modify the
$disabled_roles
or $enabled_roles
array to match your specific needs
- Test the changes while logged in as different user roles
- Remember that some themes might require additional CSS adjustments if they rely on admin bar spacing