skip to Main Content

I am looking for more performant code for selecting multiple WordPress roles as a check to run some code:

 if ( current_user_can( 'wholesale_customer' ) || current_user_can( 'wholesale_premium' ) || current_user_can( 'wholesale_nz') || current_user_can( 'wholesale_wa') ){
            // do something
     }

The above code works but I question is it optimal, from what I understand you can’t pass multiple roles into current_user_can as an array but more so capabilities.

2

Answers


  1. You can also check with user_roles_array like this –

    $user_roles = array( 'wholesale_customer', 'wholesale_premium', 'wholesale_nz', 'wholesale_wa' );
    foreach( $user_roles as $role ){
        if( current_user_can( $role ) ){
            // do something
        }
    }
    
    Login or Signup to reply.
  2. How about this one –

    $current_user = wp_get_current_user();
    $user_roles = $current_user->roles;
    $compare_user_roles = array( 'wholesale_customer', 'wholesale_premium', 'wholesale_nz', 'wholesale_wa' );
    foreach( $user_roles as $user_role ){
        if( in_array( $user_role, $compare_user_roles ) ){
            // echo $user_role;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search