admin管理员组文章数量:1410731
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' );
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' );
Share
Improve this question
asked Nov 27, 2019 at 22:06
MichaelMichael
2811 silver badge14 bronze badges
3
- 4 you can do that with the function get_users. – Kaperto Commented Nov 27, 2019 at 22:31
- Thank you. That worked... – Michael Commented Nov 27, 2019 at 23:03
- @Kaperto can you post your answer as an answer? – Tom J Nowell ♦ Commented Nov 27, 2019 at 23:10
1 Answer
Reset to default 2Taking @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();
本文标签: SQL User Query by Multiple Roles using PHP
版权声明:本文标题:SQL User Query by Multiple Roles using PHP 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744946841a2633833.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论