1

I am trying to query a list of user id's in WordPress using SQL IN() with the addition of them having a meta_value value of "Yes" on the meta_key "is_registered" in the wp_usermeta table but I can't seem to get this to work. It just returns 0 results. If I use just the IN() with the array of ID's, it works fine.

Here is what I am using:

SELECT DISTINCT wp_users.ID FROM wp_users LEFT JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) WHERE wp_users.ID IN(23,643,574,617,26) AND wp_usermeta.meta_key = 'is_registered' AND wp_usermeta.meta_value = 'Yes'

This must be SQL. I can't use WP_User_Query() as it's for a personal project of mine whereby I'd like to use SQL.

Can anyone see what I am doing wrong here as I've been racking my brain with it for what feels like forever now!

0

I'd simply go for WP_User_Query for this:

$args = [
  'meta_key'   => 'is_registered',
  'meta_value' => 'Yes',
  'fields'     => 'ID',
];

$user_query = new WP_User_Query($args);
  • This is actually a little dev project for myself and I am editing the WP_User_Query code through wp-includes/class-wp-user-query.php so I can understand it better so this solution will not work for me. It must be SQL. Thanks though. – mcmaster.1986 Apr 8 at 15:12
  • @mcmaster.1986 – OK, then please update your question and add that little bit of extra info. Thanks – leymannx Apr 8 at 15:14
  • @mcmaster.1986 your query works, although it only will return User ID. However, the users IN() must not have the meta key and value you specify. If you remove your IN() clause does it return any results? – Howard E Apr 8 at 17:09
  • @HowardE okay well this is interesting as when I remove the IN() clause, it doesn't return anything when infact it should.Massive head scratcher this one! – mcmaster.1986 Apr 8 at 17:19
  • @mcmaster.1986 you should double check your meta_key and values are correct then. Without the IN function, you're just selecting all users where the meta_key is what you want. – Howard E Apr 8 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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