Home › Forums › General Issues › Querying by relationship field
Hi! I have a product
type post that has a relationship ACF to one or more custom post type called cars
. How can I query for products that have certain type of cars? This is what I tried but I get an empty response.
// Array of car IDs
$cars = [1, 2, 3];
get_posts([
'numberposts' => -1,
'post_type' => 'product',
'meta_query' => [
[
'key' => 'cars',
'value' => $cars,
'compare' => 'IN',
],
]
]);
relationships store a serialized array and cannot be searched the way you are attempting.
See this article https://www.advancedcustomfields.com/resources/querying-relationship-fields/
@hube2 Thanks for the response! The article gives an example of querying for (in my case) products
by a single car
ID. What I want is querying by multiple car
IDs. Is this just not possible with ACF relationships?
Yes, you need to add a nested query with multiple values
'meta_query' => array(
'relation' => 'AND',
array(
'relation' => 'OR',
array(
'key' => 'car',
'value' => '"1"',
'compare' => 'LIKE'
),
array(
'key' => 'car',
'value' => '"2"',
'compare' => 'LIKE'
),
array(
'key' => 'car',
'value' => '"3"',
'compare' => 'LIKE'
)
)
)
The reason for the nested meta query is that if you also want to search by something else and the each thing you are searching by is in its own query.
@hube2 This actually worked for me! I was able to get all products
that have relationship to certain cars
:
// Array of car IDs
$cars = [1, 2, 3];
$cars = array_map(function ($car_id) {
return [
'key' => 'cars',
'value' => '"' . $car_id . '"',
'compare' => 'LIKE',
];
}, $cars);
get_posts([
'numberposts' => -1,
'post_type' => 'product',
'meta_query' => [
'relation' => 'AND',
[
'relation' => 'OR',
...$cars,
],
]
]);
Thank you!
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.