Reputation: 83
I am using a function to hide the WP admin bar for specific users with the following code:
//Hide admin bar for subscribers
if (current_user_can('subscriber') || !is_user_logged_in() ) {
// user can't view admin bar
show_admin_bar(false);
}
else {
show_admin_bar(true);
}
It works for subscribers
and visitors
but when logged in as an administrator
the admin bar doesn't show up on the front-end. Can anyone tell me what I'm doing wrong?
SOLUTION: The code above here works
Upvotes: 1
Views: 1577
Reputation: 2709
Use show_admin_bar
filter to hide/display the admin bar.
/**
* Checks if the user belongs to the roles.
*
* @param int/WP_User $user Either user_id or WP_User object.
* @param string/string[] $roles Single roles or array of roles.
*/
function is_user_in_role($user, $roles ) {
// Set user_id to null;
$user_obj = null;
// Check if the $user is integer.
if ( is_int( $user ) ) {
$user_obj = get_user_by( 'id', $user );
}
// Check if the $user is object.
if ( $user instanceof WP_User) {
$user_obj = $user;
}
// Bail if the $user_id is not set.
if ( null === $user_obj) {
return false;
}
// Check if the user belons to the role.
if ( is_string( $roles ) ) {
return in_array( $roles, (array) $user_obj->roles );
}
// Check if the user belongs to the roles.
if ( is_array( $roles ) ) {
$user_belong_to = true;
foreach( $roles as $role ) {
if ( ! in_array( $role, (array) $user_obj->roles ) ) {
$user_belong_to = false;
}
}
return $user_belong_to;
}
// Return false if nothing works.
return false;
}
add_filter( 'show_admin_bar', 'hide_admin_bar' );
function hide_admin_bar() {
$user = wp_get_current_user();
if ( is_user_in_role($user, 'administrator' ) ) {
return false;
} else {
return true;
}
}
Reference: https://cpothemes.com/disable-wordpress-admin-bar
Upvotes: 1
Reputation: 302
Check that Show Toolbar when viewing site is checked in your user settings.
Upvotes: 0
Reputation: 649
Try,
//Hide admin bar for subscribers
if( current_user_can('subscriber') || current_user_can('visitor') ) {
// user can't view admin bar
show_admin_bar(false);
} else {
show_admin_bar(true);
}
Updated Code:
//Hide admin bar for all users except administrators
if( current_user_can('manage_options') ) {
show_admin_bar(true);
} else {
// All other users can't view admin bar
show_admin_bar(false);
}
Upvotes: 2