6

I have 4 users roles on my wordpress platform (role1, role2, role3, role4)

I'm looking for to show front-end top bar only for Role1 Role2.

how can i add a condition on this code to show it only for this 2 roles?

function wpc_show_admin_bar() {
  return true;
}
add_filter('show_admin_bar' , 'wpc_show_admin_bar');

thanks

2 Answers 2

11

You can disable the admin bar via function:

show_admin_bar(false);

So with that in mind, we can hook into after_setup_theme and hide the admin bar for all users except administrator and contributor:

function cc_wpse_278096_disable_admin_bar() {
   if (current_user_can('administrator') || current_user_can('contributor') ) {
     // user can view admin bar
     show_admin_bar(true); // this line isn't essentially needed by default...
   } else {
     // hide admin bar
     show_admin_bar(false);
   }
}
add_action('after_setup_theme', 'cc_wpse_278096_disable_admin_bar');

I am only using administrator and contributor as example. You can of course change this and add more roles.

4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.