Connect with us

How to Get All Users With a Specific Role

solution

How to Get All Users With a Specific Role

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) {
//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.

1
2
3
4
5
$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.

Continue Reading
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More in solution

    About Me:

    Szabi Kisded

    Hey there, I'm Szabi. At 30 years old, I quit my IT job and started my own business and became a full time WordPress plugin developer, blogger and stay-at-home dad. Here I'm documenting my journey earning an online (semi)passive income. Read more

    Sign up for my newsletter and get the YouTube Caption Scraper WordPress plugin for free
    (worth 29$)!

    All My Plugins In A Bundle:

    My AutoBlogging Plugins:

    My Online Courses:

    A Theme I Recommend:

    Featured Posts:

    To Top