使用PHP实现多角色的SQL用户查询

时间:2019-11-27 作者:Michael

我可以使用以下代码成功获取我的所有WordPress用户:

global $wpdb;
$sql = \'SELECT * FROM \' . $wpdb->users;
$users = $wpdb->get_results( $sql, \'ARRAY_A\' );
但是,我需要过滤具有多个角色的用户(仅获取“role1”和“role2”)。我尝试了各种方法,包括以下不起作用的方法:

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\' );

1 个回复
最合适的回答,由SO网友:Michael 整理而成

根据@Kaperto的建议,我做了以下工作:

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