Home > Software design >  WordPress SQL get specific user by user role
WordPress SQL get specific user by user role

Time:10-28

Hi I am trying to get specific users from the database by SQL query. Also trying to add some conditions. User role name is: Student But I can't get proper result with my code.

SELECT um.user_id, um.meta_key, um.meta_value, u.user_email 
FROM wp_usermeta AS um INNER JOIN wp_users AS u ON (u.ID = um.user_id) 
WHERE meta_key IN ('first_name', 'last_name','role') AND (meta_value NOT LIKE '%Student' AND u.user_email NOT LIKE '%@yourdomain.com')

CodePudding user response:

You can use this function to get an array of users by role.

# This goes in functions.php
function get_users_by_role($role, $orderby, $order) {
    $args = array(
        'role'    => $role,
        'orderby' => $orderby,
        'order'   => $order
    );

    $users = get_users( $args );

    return $users;
}

Then you can use it like so :

$users = get_users_by_role('student', 'user_nicename', 'ASC');

Or you could just use get_users() like this

$students = get_users( array( 'role__in' => array( 'student' ) ) );

Or

$students = get_users( 'role=student' );

Or user_query way

$user_query = new WP_User_Query( array( 'role' => 'Student' ) ); 

If you insist on using SQL, then you could use

SELECT wp_users.ID, wp_users.user_nicename 
FROM wp_users INNER JOIN wp_usermeta 
ON wp_users.ID = wp_usermeta.user_id 
WHERE wp_usermeta.meta_key = 'wp_capabilities' 
AND wp_usermeta.meta_value LIKE '%student%' 
ORDER BY wp_users.user_nicename
  • Related