How to create a roles based query in wordpress

WordPress is a really flexibile CMS, but it is not perfect and sometimes it is truly inefficiant. Lately i needed to create a query that bring back multiple users by roles. Now wordpress have a user query but it doesn’t allow you to pass an array of roles. So, let’s see a work around.

You would assume one can pass an array of roles like so:

$users_query = new WP_User_Query(
    array(
        'role'  =>  'editor',
        'orderby' => 'registered', 
        'order' => 'ASC',
        'fields' => 'all_with_meta'
    )
);
$users = $users_query->get_results();

 Simple and logical right? yep. But you must pass a string as a role and not an array.

So the work around is simple. we will create a query for each role. Like so:

// get the featured editors
$editor_query = new WP_User_Query(
    array(
        'role'  =>  'editor',
        'orderby' => 'registered', 
        'order' => 'ASC',
        'fields' => 'all_with_meta'
    )
);
$editors = $editor_query->get_results();

// get the featured admins
$administrator_query = new WP_User_Query(
    array(
        'role'  =>  'administrator',
        'exclude' => array(),
        'orderby' => 'registered', 
        'order' => 'ASC',
        'fields' => 'all'
    )
);
$admins = $administrator_query->get_results();

// get the featured contributer
$contributors_query = new WP_User_Query(
    array(
        'role'  =>  'contributor',
        'exclude' => array(),
        'orderby' => 'registered', 
        'order' => 'ASC',
        'fields' => 'all'
    )
);
$contributors = $contributors_query->get_results();

 And then using “regular” php, we will merge the arrays:

$users = array_merge( $admins, $editors,$contributors,$authors );

 Now we have one array of users with the roles we wanted. We can loop it, and do whatever we need with it.

Leave a Reply

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