skip to Main Content

Scenario:
Posts have multiple entry of values with the same key, example a single post will have multiple meta_key [drink] => meta_value

[drink] => "banana juice"
[drink] => "orange juice"
[drink] => "apple juice"

Want to find: Posts without value of orange in any entry of the meta_values with the same meta_key drink.

current method: using wp_query:

meta_query => array(array('key' => 'drink','value' => 'orange','compare' => 'NOT LIKE'));

Issue:
wp_query will still return post with meta_value "orange" in [drink] because it has other [drink] with values which is not "orange".

2

Answers


  1. Chosen as BEST ANSWER

    I have found the answer by doing 2 wp_query (1 to get all the relevant posts and 1 to get all the post that has the orange drink) and do an array_diff to get the post without the orange drink.

    Sample Code:

    $query1 = new WP_Query(array('post_type' => 'post', 'fields'=>'ids'));
                if ( $query1->have_posts() ) { 
                    while ( $the_query->have_posts() ) {$post_ids1[]=get_the_ID();}
                }
                wp_reset_query();
                
                $meta_query = array(array('key' => 'drink','value' => 'orange','compare' => 'LIKE'));
            
    $query2 = new WP_Query(array('post_type' => 'post', 'fields'=>'ids', 'meta_query'=>$meta_query));
                if ( $query2->have_posts() ) { 
                    while ( $query2->have_posts() ) {$post_ids2[]=get_the_ID();}
                }
                wp_reset_query();
    
    $result = array_diff( $post_ids1, $post_ids2 );
    

  2. In the goofy world of SQL wildcard searches you need to use a value of %orange% with NOT LIKE.

    Without the % wildcards NOT LIKE means the same thing as <> or NOT EQUAL.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search