0

I want to block multiple user roles from accessing the WordPress dashboard, I have a custom role, and I want to block it along with other roles, but I don't know how to edit the code.

the code below has one role (shopkeeper) I want to add more roles how can I do that?

function wpse66094_no_admin_access() {
    $redirect = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : home_url( '/' );
    global $current_user;
    $user_roles = $current_user->roles;
    $user_role = array_shift($user_roles);
    if($user_role === 'shopkeeper'){
        exit( wp_redirect( $redirect ) );
    }
 }

add_action( 'admin_init', 'wpse66094_no_admin_access', 100 );
1
  • 1
    have a look at in_array(). Also exit() expects a string or int parameter while wp_redirect() returns a string. Commented Jul 29, 2022 at 18:29

1 Answer 1

2

You can make an array of the roles that need to be blocked, and use array_intersect() to check if the current user is in any of those roles.

function wpse66094_no_admin_access() {
    $redirect = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : home_url( '/' );
    global $current_user;
    $blocked_roles = array( 
        'shopkeeper',
        'block-this-role',
        'block-this-role-too'
    );
    $user_roles = $current_user->roles;
    // If the user is in any of the blocked roles, redirect 'em.
    if ( ! empty( array_intersect( $user_roles, $blocked_roles ) ) ) {
        wp_safe_redirect( $redirect );
        exit;
    }
 }

add_action( 'admin_init', 'wpse66094_no_admin_access', 100 );

Thanks to @Cornell Raiu in the comments for correcting the wp_redirect() / exit code, and @TomJNowell for recommending wp_safe_redirect().

6
  • 2
    exit() expects a string or int parameter while wp_redirect() returns a string. Commented Jul 29, 2022 at 18:29
  • 1
    Touché, I was copy-n-pasting the OP's code. Will fix, thanks.
    – Pat J
    Commented Jul 29, 2022 at 18:30
  • 1
    wp_safe_redirect would be safer, and in_array would be a simpler check than empty( array_intersect(, I'd also use [] instead of array() and update the function name to use 408112 for the new question
    – Tom J Nowell
    Commented Jul 29, 2022 at 19:11
  • Hi @Pat J, I got an error when I used the code after adding the other roles.
    – KDot
    Commented Jul 29, 2022 at 19:24
  • 1
    @TomJNowell I considered using in_array() but in the case of a user with multiple roles, array_intersect() will catch any of the blocked roles in any of the user's roles. (The originally posted code only appears to check one of the user's possible roles.)
    – Pat J
    Commented Jul 29, 2022 at 19:36

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.