Need a WordPress Expert?

Hire me!

Feb28

How to Get All Users With a Specific Role

by John Kolbert | Posted in: WordPress



Sometimes as a WordPress plugin developer you want to get all of the users with a specific role. For example, maybe you want to create a plugin that emails all the “Editors” of your blog. To easily get all users of a role, use the function below.


function getUsersWithRole($role) {
//gets all users with specified role

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

The getUsersWithRole() 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.


$editors = getUsersWithRole('editor');

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

Update: 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.

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

2 Comments


RSS feed for comments on this post.

Trackbacks on this post

Links to this post will be listed here. You an add your own by linking to the TrackBack URL

  1. How to: Get all users having a specific role

    [...] to John Kolbert for this great [...]

  2. WordPress: Get Users by Role Function | Clarkson Energy Homes

    [...] Kolbert wrote a function to to get a list (array) of users by their role name. For example, he shows how to get a list of [...]

Leave a comment



By pressing submit you are granting me a perpetual, non-exclusive licence to reproduce, paraphrase, and display your words, name, and/or website on this domain. All comments subject to moderation at my discretion.