Custom code for disabling the WordPress admin bar for specific user roles

Emily W Dec 18, 2024 User Management
How can I hide the admin bar at the top of my website for certain users?
What is the best way to programmatically disable the WordPress admin bar for specific user roles using a custom function?
Andy answered Dec 18, 2024

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

  1. Add to your theme's functions.php file
  2. Create a site-specific plugin
  3. Use a code snippets plugin like "Code Snippets"

Plugin Solutions

If you prefer a plugin solution, these options work well:

  1. User Role Editor - Offers granular control over user roles and capabilities, including admin bar visibility
  2. AdminBar - Simple plugin to control admin bar visibility per user role
  3. 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