How to: Get all users having a specific role

March 4, 2009 at 9:00 am

When developing plugins or advanced WordPress theme, sometimes it can be useful to get all the users belonging to a specific role, for exemple, all administrators. My friend John Kolbert just wrote a great function to do that.

The first thing to do is to create the function. To do so, paste the following code in your functions.php file:

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

Once done, you can call the function this way:

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

Thanks to John Kolbert for this great recipe!

Tags: