Site icon Hip-Hop Website Design and Development

Negative meta_query if storing multiple post_meta values with shared meta_key

WordPress supports storing multiple post meta values using the same meta key. For example a post can have multiple instances of meta_key ‘pet’ with meta_value ‘cat’, ‘dog’, and ‘fish’. This is super useful when using get_post_meta because you can get an array of all values without worrying about storing serialized arrays of data.

It’s also really useful when using a meta query, because you can query any post where meta_key ‘pet’ = ‘cat’, and get posts where any instance of ‘pet’ is equal to ‘cat’, regardless of how many other instances of the meta key may be associated with the post with different values.

But is the opposite (e.g. != or NOT LIKE or NOT IN) possible? I’m using the following and it’s returning lots of posts that have one instance of meta_key ‘pet’ = ‘cat’.

$pet_owners = new WP_Query([
  'post_type' => 'pet_owner',
  'posts_per_page' => -1,
  'meta_query' => [
    'key' => 'pet',
    'value' => 'cat',
    'compare' => '!='
  ]
]);