I see many people using the after_setup_theme
action instead of the show_admin_bar
filter, but this one works as well. I would say that the only difference is that the filter might be overwritten, but I see nothing wrong in that.
function wpc_show_admin_bar() {
// Add the roles to exclude from having admin bar.
$excluded_roles = [ 'role3', 'role4' ];
return is_user_logged_in() && ! array_intersect( wp_get_current_user()->roles, $excluded_roles);
}
add_filter('show_admin_bar', 'wpc_show_admin_bar');
Nice and easy, you just need to add the roles you want to the $excluded_roles
array. The function will only return true if the user is logged in and it doesn't have any of the excluded roles.