2

I can successfully get all my WordPress users using the following code:

global $wpdb;
$sql = 'SELECT * FROM ' . $wpdb->users;
$users = $wpdb->get_results( $sql, 'ARRAY_A' );

However, I need to filter the users with multiple roles (only get "role1" and "role2"). I have tried various methods including the following which does not work:

global $wpdb;
$sql = '
    SELECT ID, display_name FROM wp_users 
    INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id )  
    INNER JOIN wp_usermeta AS mt1 ON ( wp_users.ID = mt1.user_id ) 
    WHERE 1=1 
    AND ( 
      ( 
        ( 
          ( mt1.meta_key = 'wp_capabilities' AND mt1.meta_value LIKE '%role1%' )
        ) 
        AND 
        ( 
          ( 
            ( mt1.meta_key = 'wp_capabilities' AND mt1.meta_value LIKE '%role2%' )
          )
        )
      )
    ) 
    ORDER BY user_login ASC
    ';
$users = $wpdb->get_results( $sql, 'ARRAY_A' );
  • 4
    you can do that with the function get_users. – Kaperto Nov 27 '19 at 22:31
  • Thank you. That worked... – John Smithly Nov 27 '19 at 23:03
  • @Kaperto can you post your answer as an answer? – Tom J Nowell Nov 27 '19 at 23:10
1

Taking @Kaperto's advice, I did the following which works:

$user_query = new WP_User_Query( array(
    'role__in'    => ['role1','role2''],
    'orderby' => 'meta_value_num',
    'order' => 'ASC',
) );   
$users = $user_query->get_results();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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