0

The intention is to search for customers who do not have coupon X or do not have any coupon.

    $query = array (
        'post_type'      => 'clients',
        'meta_query'=> array(
            'relation' => 'OR',
            array(
               'key' => 'cupom',
               'value' => $idCupom,
               'compare' => '!=',
        ), array(
              'key' => 'cupom',
              'compare' => 'NOT EXISTS',
              'value' => '',
        )),
        'posts_per_page' => -1,
    );

I am doing according to other answers I found on the web, but the query returns wrong when it finds a post that has a meta_value different from the one searched.

  • why did you write 'key' => 'cupom' ? – Swartex Nov 25 '19 at 15:29
  • Note that this will be an expensive query that gets exponentially more expensive as the post meta table gets larger. You never want to tell the DB what you don't want, you want to tell it what you do want. Also, never set posts_per_page to -1. Give it a high number you never expect to reach, but never -1 – Tom J Nowell Nov 25 '19 at 16:01
  • @swartex 'cupom' is the meta_key i want to search and compare – José Diniz Nov 25 '19 at 16:18
  • @tomjnowell this is a revers query because i want to add post meta on clients don't have 'cupom' – José Diniz Nov 25 '19 at 16:20
  • if it's a one time task then you would be better off with a WP CLI command and fetching all the posts, then checking in PHP, paging through them in batches – Tom J Nowell Nov 25 '19 at 17:35

Your Answer

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

Browse other questions tagged or ask your own question.