Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question

3 Answers

I managed to solve this by using this function:

function get_clients() { 

    $users = array();
    $roles = array('subscriber', 'custom_role1', 'custom_role2');

    foreach ($roles as $role) :
        $users_query = new WP_User_Query( array( 
            'fields' => 'all_with_meta', 
            'role' => $role, 
            'orderby' => 'display_name'
            ) );
        $results = $users_query->get_results();
        if ($results) $users = array_merge($users, $results);
    endforeach;

    return $users;
}

Then in my theme I can do this:

$users_array = get_clients();
share|improve this answer
This is the best option I have come across. Thanks. – Jake Oct 12 '12 at 18:44

You can also do this via a single call to get_users or using a single WP_User_Query by making use of the meta_query argument:

global $wpdb;
$blog_id = get_current_blog_id();

$user_query = new WP_User_Query( array(
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
            'value' => 'role_one',
            'compare' => 'like'
        ),
        array(
            'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
            'value' => 'role_two',
            'compare' => 'like'
        )
    )
) );

The meta_query is pulled from how WP_User_Query handles the role parameter, if you're interested.

share|improve this answer
Works like a charm! Thanks for sharing. – Rilwis Mar 13 at 12:17

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.