How WordPress can list users with specific capabil

2019-06-27 04:33发布

问题:

Is there a way to list only the users that has a specific capability, such us "publish_posts" ?

回答1:

You can list users with WP_User_Query, but afaik you can only return different roles, not permissions, maybe that's already what you want! There's also a site where you can see the different roles in the wordpress documentation.



回答2:

You can just retrieve all users. Then loop through them in a foreach. Check if the user has a specific capability then push the users to another array and use that array to list them.

$all_users = get_users();
$specific_users = array();

foreach($all_users as $user){

    if($user->has_cap('specific_capability')){
        $specific_users[] = $user;
    }

}

NOTE: It seemed a nice quick and dirty solution at the time, but now I would recommend writing a query. I do not have the time to investigate this for you, so if the one downvoting this would be so kind to answer this question instead of downvoting an answer which was an actual help to the inquirer, that would be nice.



回答3:

To select users with certain capabilities you can use WP_User_Query with meta_query parameter, because WP stores capabilities as a serialized string in user_meta table. Also remember that due to availability to have multisite installation capabilities name in user meta looks like wp_table_prefix_capabilities.

global $wpdb;
// meta-key name
$capabilities_field_name=$wpdb->prefix.'capabilities';
//array as argument for our query
$qargs=[
     'role' => ['Customer'], // use this if you need to query by role at the same time
     'meta_query'=>
         [
            'relation' => 'OR', // optional if you'll need to select more than
                                //  one capability just add this and create same array
                               // as down below describing what are you looking for 
             [
                'key' => $capabilities_field_name,
                'value' => 'your_role_name',
                'compare' => 'LIKE',
             ],

       // here could be same array [key,value,compare]... as above with another capability      
       // but you'll need to add extra argument showing relationship between them see above 'relation parameter'

         ],
     'number'=> -1 // to select all users
 ];

$usersQuery=new WP_User_Query($qargs); // instantiate UserQuery with $qargs

$users=$usersQuery->get_results(); // get all results as array of WPUser objects

Hope it helps somebody:) Note [vars] could be substituted to array(vars), I like [] short syntax but it's supported only since php 5.4.