Hi I’m trying to select users with a particular role only, using the following sql statement…
SELECT DISTINCT ID, u.user_login, u.user_nicename, u.user_email
FROM wp_users u, wp_usermeta m
WHERE m.meta_key = 'wp_capabilities'
AND m.meta_value LIKE '%supplier%'
ORDER BY u.user_registered
However, it reurns the whole table. What am I doing wrong?
PS this needs to be a SQL select as I’m doing this in myphpadmin to export the data to csv.
Thanks in advance!
Double-check your SQL syntax. It sounds like you want to do a
JOIN
… But you’re not building the query correctly.It should be something more like:
You have to tell the query how you’re relating the user meta to the user.
Also note that I’m using
$wpdb->
rather thanwp_
. This is important if you ever expect to use this query in a plugin on a site with a database prefix other than “wp.” If you’re running things directly in SQL, though, you should switch back.There’s a (query-)class built into core:
new WP_User_Query;
This then allows looping through the user objects:
For further examples, or querying users by other fields, please consult the codex.