Remove the WordPress Admin Bar for Specific User Roles

Lukas K. Dec 31, 2024 User Experience
How can I hide the admin bar at the top of my WordPress site for certain users?
What PHP code can I use to remove the WordPress admin bar for specific user roles programmatically?
Andy answered Dec 31, 2024

Solution Using Custom Code

Function-Based Approach

Add this code to your theme's functions.php file or in a site-specific plugin:

This code removes the admin bar for specific user roles:

function remove_admin_bar_for_roles() {
    if (!is_user_logged_in()) {
        return;
    }
    
    $user = wp_get_current_user();
    $roles_to_hide = array('subscriber', 'customer'); // Modify these roles as needed
    
    if (array_intersect($roles_to_hide, $user->roles)) {
        add_filter('show_admin_bar', '__return_false');
    }
}
add_action('init', 'remove_admin_bar_for_roles');

Alternative Approach with Capability Check

This version checks user capabilities instead of roles:

function remove_admin_bar_by_capability() {
    if (!current_user_can('publish_posts')) { // Change capability as needed
        add_filter('show_admin_bar', '__return_false');
    }
}
add_action('init', 'remove_admin_bar_by_capability');

CSS-Based Solution (Optional)

If you prefer to hide it with CSS, add this to your theme's CSS file:

function hide_admin_bar_with_css() {
    if (!current_user_can('publish_posts')) {
        echo '<style type="text/css">
            #wpadminbar { display: none !important; }
            html { margin-top: 0 !important; }
        </style>';
    }
}
add_action('wp_head', 'hide_admin_bar_with_css');

Plugin Solutions

If you prefer using a plugin, here are reliable options:

  1. Admin Bar Disabler - Simple plugin with role-based control
  2. Hide Admin Bar Based on User Roles - More advanced options for specific roles

Notes

  • The first code example is the most flexible as you can easily modify the $roles_to_hide array
  • Choose the capability-based approach if you want to target users based on what they can do rather than their role
  • Place the code in functions.php or ideally in a site-specific plugin
  • The CSS solution should be used only if the PHP solutions don't work for your specific case
  • Test thoroughly after implementation as removing the admin bar might affect other functionality that depends on it