How WordPress Can List Users With Specific Features

Is there a way to list only those users who have a specific feature, such as publish_posts?

+4
source share
3 answers

You can specify WP_User_Query users, but afaik you can return only different roles, not permissions, maybe this is what you want! There is also a website where you can see various roles in the Wordpress documentation.

+3
source

You can simply download all users. Then navigate through them in the foreach. Check to see if the user has a specific ability, then push the users to another array and use this 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: At the time, this seemed like a nice quick and dirty solution, but now I would recommend writing a query. I don’t have time to research this for you, so if one downvoting it would be so kind as to answer this question, instead of having a downvoting answer that was the actual help of the inquiry officer, that would be good.

+7
source

To select users with certain capabilities, you can use WP_User_Query with the meta_query parameter, since WP stores the capabilities as a json string in user_meta. Also remember that due to the availability of multi-user installation capabilities, the name in the user thrower 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"', //rolename placed in "" in json it is quoted '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 this helps someone :) Note. [Vars] can be replaced with an array (vars), I like the [] short syntax, but only supported with php 5.4.

+5
source

All Articles