This WordPress tutorial shows you how to get all users with a specific role. This can be used for mass emailing subscribers, mass changing user roles, or whatever your developing heart desires!
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.
1
2
3
4
5
6
function getUsersWithRole($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.
1
2
3
4
5
$editors = getUsersWithRole(‘editor’);
foreach($editors as $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.