Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    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.

    Thread Starter Timothy Jacobs

    (@timothyblynjacobs)

    Thanks bcworkz.

    Arg, that is quite annoying. So I’d want something like this for my meta_query array.

    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 EXISTS in 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();
    Thread Starter Timothy Jacobs

    (@timothyblynjacobs)

    Thanks Nicohrn,

    That is what I am doing more or less, I just changed to now do a meta_compare of == and the meta_value as 0.

    It appears, after digging into the WP_User_Query class, however, that the problem is that WordPress treats the role query variable, as a meta_query as such the relation of OR makes it so that it effectively negates its usage.

    Got to figure out someway to inverse the logic now.

    Moderator bcworkz

    (@bcworkz)

    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.

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘WP Metadata User Query on non-existent fields’ is closed to new replies.