Home › Forums › General Issues › get_terms() with multiple values
I have a scenario where I need to query a taxonomy with multiple values. Here is the basic idea:
$people_array = array(73227,970674,17293);
$args = array(
'taxonomy' => 'people',
'meta_query' => array(
array(
'key' => 'person_id',
'value' => $people_array,
'compare' => '='
),
)
);
$people = get_terms( $args );
However, passing an array in there does not appear to work. It apparently has to be constructed like this:
$args = array(
'taxonomy' => 'people',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'person_id',
'value' => 73227,
'compare' => '='
),
array(
'key' => 'person_id',
'value' => 970674,
'compare' => '='
),
array(
'key' => 'person_id',
'value' => 17293,
'compare' => '='
)
)
);
$people = get_terms( $args );
That works! But how do I construct this dynamically from a list of IDs? I tried something like this, which is to build an array of arrays…
$people_array = array(73227,970674,17293);
$person_ids_array = array();
for ($x = 0; $x < count($people_array); $x++) {
$tempArray = array('key' => 'person_id', 'value' => $people_array[$x], 'compare' => '=');
array_push($person_ids_array, $tempArray);
}
$args = array(
'taxonomy' => 'people',
'meta_query' => array(
'relation' => 'OR',
$person_ids_array,
)
);
$people = get_terms( $args );
That doesn’t work either. I’m stymied. There must be some way to do this…
Thank you for any help you can provide!
UPDATE: For anyone else who encounters this…
It turns out, the first option DOES work. You can pass an array to a meta_value. HOWEVER, the operator ‘=’ does not work. Changing the compare to ‘IN’ works for my scenario. Final code:
$people_array = array(73227,970674,17293);
$args = array(
'taxonomy' => 'people',
'meta_query' => array(
array(
'key' => 'person_id',
'value' => $people_array,
'compare' => 'IN'
),
)
);
$people = get_terms( $args );
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.