1

Is there a way to use the get_users() function, or maybe another way, to retrieve all users of a custom user capability?

For example, I have given a select number of users the capability of 'team_member', which allows a user to access areas non team members cannot.

Due to the nature of the site, simply creating a new role is not an option. I'm also not able to just add the capability to an already registered role.

I assumed there would be a way to do this using get_users, but there doesn't seem to be. Unless I'm wrong?

$args = array(

    'role' => 'team_member'

); 

get_users( $args );

If there isn't a way to get users from custom cap, my next idea is to not use custom capabilities but instead insert the same key in a user's usermeta. This will then at least allow me to include a meta_query in the get_user $args.

1

I gave it a test run. First, I added a custom capability to a specific user, using following code

$user = new WP_User( $user_id );
$user->add_cap( 'team_member' );

Luckily, this user can be retrieved using below code, as you suggested

$args = array(
    'role' => 'team_member'
); 

get_users( $args );

Which implicitly work like below

$args = array (
    'meta_query' => array(
        array(
            'key'     => 'wp_capabilities',
            'value'   => '%team_member%',
            'compare' => 'LIKE'
        ),
    )
);

$wp_user_query = new WP_User_Query( $args );

Reference: WP_User_Query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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