Get all wordpress users having a specific role

March 12, 2009 · Print This Article

Sometimes as a WordPress plugin developer or a WordPress theme developer, you want to get all of the users with a specific role.

For example, all editors.

To easily get all users of a role, the first thing to do is to create the function.

To do so, paste the following code in your functions.php file:

function getAllUsersWithRole($role) {
$wp_user_search = new WP_User_Search($usersearch, $userspage, $role);
return $wp_user_search->get_results();
}

The getAllUsersWithRole() function returns an array containing the user IDs of all users with the role you specified. To use this, just set the function to a variable and loop through the array. You can call the function this way:

$editors = getAllUsersWithRole('editor');
foreach($editors as $editor){
//$editor now holds the user ID of an editor
}

It’s important to note that this function only works on admin pages of WordPress (such as plugin or theme options pages). It is not available for theme template usage.


Related articles:

Your choice for site templates and wordpress themes

Comments

One Response to “Get all wordpress users having a specific role”

  1. fabien on July 27th, 2009 10:01 am

    Hi,

    This piece of code just saved my life !

    Thanks a lot for this ! But, it only gives me 50 users, and i need to get all of them

    Do you know how to do that ?

    thanks.

Got something to say?

You must be logged in to post a comment.