Reputation: 5205
I am using wordpress 4.9.7
and I am using advanced custom fields 4.4.12
.
In my backend I have a post type that is called coins
, which has a relationship field called related_coins
and a text-field, which is called algorithm
. Basically my relationship field creates a relationship to the custom post type products
. So product can have a relationship with several coins.
I currently only can filter by post type. However, I would like to filter by the custom field algorithm
of the post type coin
.
I tried the following:
function graphic_card_products_query( $args, $field, $post_id ) {
$args['meta_query'] = array(
array(
'key' => 'algorithm', // name of custom field
'value' => 'related_coins',
'compare' => 'LIKE'
)
)
// return
return $args;
}
// filter for every field
add_filter('acf/fields/relationship/query/name=related_coins', 'graphic_card_products_query', 10, 3);
Basically I am trying to get a list of all values that the custom field algorithm
has and hand it as a filter option back to the relationship field related_coin
.
Currently I do not get anything back.
Any suggestions what I am doing wrong?
Upvotes: 5
Views: 5938
Reputation: 469
I have tested this, using your code as a base, and I can confirm it works for me. I'll detail what I did.
First, you may have spotted it, but you are missing a semicolon after your meta_query
. So I fixed that.
$args['meta_query'] = array(
array(
'key' => 'algorithm', // name of custom field
'value' => 'related_coins',
'compare' => 'LIKE'
)
); // <-- this one!
Next, I made sure that the field I was filtering was indeed a 'Relationship' field, not any of the other 'relational' fields types (Post Object, Links, Taxonomy, for example). They have their own filters (ACF Reference: Filters)
Lastly, I confirmed that the meta_query was correct and what I was expecting. So your meta_query is looking for products with the custom field 'algorithm' and a value of 'related_coins'
. (It may well be correct, but make sure the value you want is 'related_coins'
as that sounds rather like a key, not a value). You're then using the LIKE operator which will match values with 'related_coins' contained within the value. For example, it will match '123_related_coins'
and 'related_coins_123'
, as well as just 'related_coins'.
As I said, this may be what you want, but just understand that is what the meta query means.
Hope this helps!
Upvotes: 3