Wordpress: get users by role
Here's a little function I cooked up to fetch users by their roles.
Written by Daniel, April 4, 2010
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.
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;
}
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:
$admins = get_users_by_role('administrator');
foreach($admins as $admin)
{
echo $admin -> user_nicename . '<br />';
}
Outputs something like:
admin
admin2
If anyone knows of a simpler way of doing this, please let me know.
Hi, I’m looking into doing the same thing myself, but have been thinking about using INNER JOIN in the query rather than get_userdata() for each of the results. Might be a bit more efficient, but I’m not sure?
$sql = "SELECT * FROM $wpdb->users INNER JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id WHERE 1=1 AND wp_usermeta.meta_key = 'wp_capabilities' AND wp_usermeta.meta_value LIKE '%administrator%' OR wp_usermeta.meta_value LIKE '%editor%'";good tip on using {$wpdb -> users} instead of the table names, thanks!
Comment by Björn Rixman — May 7, 2010 @ 10:57 am
ah, sorry about that, I misread your code – you’re using JOIN aswell in the query…
Comment by Björn Rixman — May 7, 2010 @ 11:00 am
Hey Björn,
yeah the formatting isn’t optimal there.
I think you have a good point, it’s probably more efficient to just use straight SQL and check wether a result came back. It’ll save a loop at least..
I’ll experiment a bit when I get the time.
Thanks for the tip!
Comment by Daniel — May 7, 2010 @ 11:19 am