Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have a custom plugin which queries users and usermeta, but I now need to filter admins out of the results. A very simplified version of my sql query is:

SELECT * FROM usermeta LEFT JOIN users ON users.ID = user_id WHERE meta_key = 'last_name' AND user_role != 'admin' ORDER BY meta_value ASC LIMIT 0, 25 user_role is not a field, and i saw how it is stored as a config string, but i don't see how to make an equivalent query to this. am i missing something?

thanks.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

You can use this function:

// get users with specified roles
function getUsersWithRole( $roles ) {
    global $wpdb;
    if ( ! is_array( $roles ) )
        $roles = array_walk( explode( ",", $roles ), 'trim' );
    $sql = '
        SELECT  ID, display_name
        FROM        ' . $wpdb->users . ' INNER JOIN ' . $wpdb->usermeta . '
        ON          ' . $wpdb->users . '.ID             =       ' . $wpdb->usermeta . '.user_id
        WHERE       ' . $wpdb->usermeta . '.meta_key        =       \'' . $wpdb->prefix . 'capabilities\'
        AND     (
    ';
    $i = 1;
    foreach ( $roles as $role ) {
        $sql .= ' ' . $wpdb->usermeta . '.meta_value    LIKE    \'%"' . $role . '"%\' ';
        if ( $i < count( $roles ) ) $sql .= ' OR ';
        $i++;
    }
    $sql .= ' ) ';
    $sql .= ' ORDER BY display_name ';
    $userIDs = $wpdb->get_col( $sql );
    return $userIDs;
}
share|improve this answer
    
nice: D you can also do this using the WP_User_Search class from wp-admin/includes/user.php –  onetrickpony Dec 21 '10 at 10:49
    
As valid as your answer is, it highlights everything that's wrong in the WP RBAC. –  Denis Dec 22 '10 at 3:18
    
Denis, I agree with you, WP RBAC is a pita :). Thanks the answer though, it helped lead me down a good path. –  benstraw Dec 31 '10 at 6:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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