Home › Forums › General Issues › WP_Query to exclude posts by multiple meta keys
Hi Friends,
I cannot, for the life of me, figure out what I have done wrong here. I have a post type called “people”. I have 2 custom fields (among others) that are true/false for “alumni” and “intern_dev”.
I want to exclude from the list of people, anyone who has a value of “true” (or 1) for the “alumi” and/or “intern_dev” fields.
Here’s the custom fields:
acf_add_local_field_group(array (
'key' => 'group_peoplestat',
'title' => 'People Status',
'fields' => array (
array (
'key' => 'field_alum',
'label' => 'Alumni?',
'name' => 'alumni',
'type' => 'true_false',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'wrapper' => array (
'width' => '',
'class' => '',
'id' => '',
),
'message' => '',
'default_value' => 0,
),
array (
'key' => 'field_intern',
'label' => 'Intern Dev?',
'name' => 'intern_dev',
'type' => 'true_false',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'wrapper' => array (
'width' => '',
'class' => '',
'id' => '',
),
'message' => '',
'default_value' => 0,
),
),
'location' => array (
array (
array (
'param' => 'post_type',
'operator' => '==',
'value' => 'people',
),
),
),
'menu_order' => 4,
'position' => 'side',
'style' => 'default',
'label_placement' => 'top',
'instruction_placement' => 'label',
'hide_on_screen' => '',
'active' => 1,
'description' => '',
));
and here’s my query:
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'alumni',
'value' => '0',
'compare' => '==',
),
array(
'key' => 'alumni',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'intern_dev',
'value' => '0',
'compare' => '==',
),
array(
'key' => 'intern_dev',
'compare' => 'NOT EXISTS'
),
)
);
I have tried everything I can think of, and for some reason I am just not able to get this to stick. I’ve var_dumped the query, looked at the db, anything I could think of. Can someone help?
The reason is OR
If alumi == 1 and intern_dev == 0 then one OR the other == 0 and will be returned.
You need to use nested queries
'meta_query' => array(
'relation' => 'AND',
array(
'relation' => 'OR',
array(
'key' => 'alumni',
'value' => '0',
'compare' => '==',
),
array(
'key' => 'alumni',
'compare' => 'NOT EXISTS',
)
),
array(
'relation' => 'OR',
array(
'key' => 'intern_dev',
'value' => '0',
'compare' => '==',
),
array(
'key' => 'intern_dev',
'compare' => 'NOT EXISTS',
)
)
),
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.