1

I've been stuck on a problem for a while now and I can't seem to figure it out.

I want to query posts and only display them if their 2 meta values checked contain the ones I have queried.

For example:

If a post had 123 and 321 then I want them to be displayed. But if it had 123 and 123 then it shouldn't be displayed and vice versa.

I have been looking at this code and I cant figure it out:

array(
       'key' => 'featured',
       'value' => 'yes',
       'compare' => 'NOT NULL',
    ),
 array(
       'key' => 'type',
       'value' => 'event',
       'compare' => 'NOT NULL',
    )

So just to clarify:

  • if featured value is "yes" AND type value is "event" => it should be displayed

but

  • if featured value is "yes" AND type value is "party" => it shouldn't be displayed.

Sorry if this doesnt make sense.

Thanks, Dazeh.

2 Answers 2

1

I believe what you are looking for is the relation parameter in meta_query. I'm assuming you are using the WP_Query class to make the call given your syntax in the example. You might want to ensure that no other plugins are forcing the relation parameter to be "OR" instead of the default "AND" by hooking into pre_get_posts.

$meta_query_AND = array(
    'meta_query' => array(
        'relation' => 'AND',
        array(
               'key' => 'featured',
               'value' => 'yes',
               'compare' => 'NOT NULL',
            ),
         array(
               'key' => 'type',
               'value' => 'event',
               'compare' => 'NOT NULL',
            )
     )
    );
$test_query = new WP_Query( $meta_query_AND );

The first step would be to evaluate the meta_query => relation value in your wp_query result.

2
  • 1
    relation is AND by default. I think the problem is 'compare' argument...
    – gmazzap
    Commented Apr 10, 2014 at 12:23
  • good point - I was thinking that it was set by default but have seen in several plugins where the queries are dirtied by an unprotected relation set to OR and your answer for compare is a good point as well in order to be most explicit in the query. Commented Apr 10, 2014 at 15:37
1

'compare' should be '=' because you are comparing exact values, also 'relation' have to 'AND'. Both should be default, but better to be sure

$meta_query = array (
  array(
    'key' => 'featured',
    'value' => 'yes',
    'compare' => '='
  ),
  array(
    'key' => 'type',
    'value' => 'event',
    'compare' => '='
  ),
  'relation' => 'AND'
);

$featured_events = new WP_Query( array( 'meta_query' => $meta_query ) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.