users – Get multiple roles with get_users

Question

The problem with using array_merge is that you can’t use pagination. I really like Andy Mercer 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 new INNER JOIN for each meta query).

My solution is to use a regular expression meta query:

<?php

global $wpdb;
$blog_id = get_current_blog_id();

$roles = array('editor', 'administrator');
$meta_query = array(
    'key' => $wpdb->get_blog_prefix($blog_id) . 'capabilities',
    'value' => '"(' . implode('|', array_map('preg_quote', $roles)) . ')"',
    'compare' => 'REGEXP'
);
$user_query = new WP_User_Query(array(
    'meta_query' = array($meta_query)
));

?>

This generates a query that looks something like:

array(
    'meta_query' => array(
        array(
            'key' => 'wp_capabilities'
            'value' => '"(editor|administrator)"'
            'compare' => 'REGEXP'
        )
    )
);

0
blogjunkie 10 years 2012-01-18T07:09:07-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse