Wordpress: get users by role
Here's a little function I cooked up to fetch users by their roles.I needed a simple way to get all users by their roles, and none of WP's built in functions seemed to be able to do this. [sourcecode lang="PHP"] public function get_users_by_role($role = 'all') { global $wpdb; $query = $wpdb -> prepare("SELECT {$wpdb -> users}.ID as `id`, {$wpdb -> usermeta}.meta_value as `capabilities` FROM {$wpdb -> users} JOIN {$wpdb -> usermeta} ON {$wpdb -> users}.ID = {$wpdb -> usermeta}.user_id WHERE {$wpdb -> usermeta}.meta_key = 'wp_capabilities'"); $userdata = $wpdb -> get_results($query); $users = Array(); foreach($userdata as $data) { $caps = unserialize($data -> capabilities); if($caps[$role] == true || $role == 'all') { $users[] = get_userdata($data -> id); } } return $users; } [/sourcecode]
There's a pretty long query in there which pretty much just selects the ID from the wp_users table and the wp_capabilities value from the wp_usermeta table.
Then there's a loop which checks that the selected user id has the wanted role, and then an array of all users with their data is returned. Pretty simple.
Use it like this:
[sourcecode lang="PHP"]
$admins = get_users_by_role('administrator');
foreach($admins as $admin)
{
echo $admin -> user_nicename . '<br />';
}
[/sourcecode]
Outputs something like:
admin
admin2
If anyone knows of a simpler way of doing this, please let me know.
Folk siger