WP Metadata User Query on non-existent fields
-
Hi all,
I am using the WP_User_Query class, and the meta search ( meta_key, meta_value, meta_compare ) capabilities.
I am trying to do a search for all users who do not have a certain meta_key set to true. However, if the metadata does not exist for the user, then WP_User_Query doesn’t return that user, despite the fact that I am using != as the comparison.
Here is my code, any thoughts?
$query = new WP_User_Query( array( 'role' => 'some_slug, 'meta_key' => 'some_sort_of_meta_key', 'meta_value' => 1, 'meta_compare' => "!=", 'number' => 25, 'offset' => $user_offset ) ); $users = $query->get_results();Thanks!
-
By requiring a value to not equal something, you are still requiring the key to exist in order to confirm it does not equal something. The lack of a key causes the result of the comparison to be undefined, neither true nor false. You need to use the ‘meta_query’ form where you can supply multiple conditions.
One condition can be what you have, then OR (NOT )EXISTS. There is a bug in the posts query class where one must provide a value for EXISTS and NOT EXISTS conditions for the query to work even though it’s illogical and is not used. I don’t know if the same problem applies to users or not.
Thanks bcworkz.
Arg, that is quite annoying. So I’d want something like this for my
meta_queryarray.So I have done it now using a meta_query, but now it seems to be completely ignoring the role parameter. Strange. Any ideas?
You probably need to use
NOT EXISTSin the meta_compare in some fashion.This might do the trick, although it is untested:
$query = new WP_User_Query(array( 'role' => 'some_slug, 'meta_query' => array( 'relation' => 'OR', array( 'meta_compare' => '!=', 'meta_key' => 'some_sort_of_meta_key', 'meta_value' => '1', ), array( 'meta_compare' => 'NOT EXISTS', 'meta_key' => 'some_sort_of_meta_key', ) ), 'number' => 25, 'offset' => $user_offset )); $users = $query->get_results();Thanks Nicohrn,
That is what I am doing more or less, I just changed to now do a
meta_compareof==and themeta_valueas0.It appears, after digging into the
WP_User_Queryclass, however, that the problem is that WordPress treats therolequery variable, as ameta_queryas such therelationofORmakes it so that it effectively negates its usage.Got to figure out someway to inverse the logic now.
I don’t think inverting the logic will be entirely successful, you will probably need to directly edit the SQL WHERE clause using the ‘pre_user_query’ action. To avoid fragile string manipulation code, you may be better off dropping whatever WP comes up with and completely defining this part as is appropriate.
The topic ‘WP Metadata User Query on non-existent fields’ is closed to new replies.