I’ve got some code like this:
$query_args = array(); $query_args['fields'] = array( 'ID', 'display_name' ); $query_args['role'] = 'subscriber'; $users = get_users( $query_args ); foreach ($users as $user) $users_array[$user->ID] = $user->display_name;
I want to get more roles and also include contributor
, author
and some custom roles I created with the Role Scoper plugin e.g. Manager
, etc. Any ideas how I can do this with get_users
?
Thanks
Fastforward to WordPress 4.4 – it will support the
role__in
attribute!It looks like WordPress 4.4 is our lucky version number, because it will support both the
role__in
androle__not_in
attributes of theWP_User_Query
class.So to include the subscriber, contributor and author roles, we can simply use:
Check out the ticket #22212 for the whole story!
You can also do this via a single call to
get_users
or using a singleWP_User_Query
by making use of themeta_query
argument:The
meta_query
is pulled from howWP_User_Query
handles therole
parameter, if you’re interested.I managed to solve this by using this function:
Then in my theme I can do this:
Since
get_users()
returns an array of users that match the query string given as a param. Just run theget_users()
query for every role you want separately and merge the results. You can then loop through$users
the same way you would have otherwise.The problem with using
array_merge
is that you can’t use pagination. I really like @Andy Adams’s solution, but if you’re searching on many roles, using his meta query will result in a very slow query (internally it does a newINNER JOIN
for each meta query).My solution is to use a regular expression meta query:
This generates a query that looks something like:
You could simply merge more user query results. Let’s say you want to include both
Author
andEditor
roles. Define the query for each case then use array_merge to consolidate into a single array.All the parameters from the function get_users are optional. If you specify nothing you will get an array that contains objects corresponding to each and every user of the current blog, including ones with custom roles.
Hi you can use this easy way