Hi all,
I have 2 custom post types:
– Homes
– Places
In homes, I have a Post Object relationship field to select a Place. The field it is set to return the object instead of the ID – if that makes a difference.
Now, in Places post type I am trying to setup a relationship field, that will show items from the Homes post types. But I also want to filter them based on the Place ID that is currently edited.
I found some topics in the forum, like this one:
https://support.advancedcustomfields.com/forums/topic/how-can-i-filter-a-posts-relationship-field-by-the-current-category-edit-screen/
I wrote my function:
function related_homes( $args, $field, $post_id ) {
$meta_query[] = array(
'key' => 'place',
'value' => $post_id,
'compare' => 'LIKE'
);
$args['meta_key'] = $meta_query;
// return
return $args;
}
But I get no matches.
Could someone offer some insights on how to go for it?
Also, how I could go to var_dump() the $args, $field etc for debugging purposes in this function?
It’s using ajax and if I var_dump I simply get nothing.
First question, does your post object field allow multiple of single values. If it contains multiple then you query is close, it should be
array(
'key' => 'place',
'value' => '"'.$post_id.'"',
'compare' => 'LIKE'
);
If it only contains 1 then it should be
array(
'key' => 'place',
'value' => $post_id
'compare' => '='
);
The next problem is with what your returning for args
function related_homes( $args, $field, $post_id ) {
// since $meta_query array does not exist yet you shouldn't use
// $meta_query[] =
$meta_query = array(
array(
'key' => 'place',
'value' => $post_id,
'compare' => 'LIKE'
)
);
// the correct argument key is 'meta_query'
$args['meta_query'] = $meta_query;
// return
return $args;
}
In the above function, is it possible to get the post_type somehow?
I am thinking to use this same field in more post_types, so it would be nice if I could do something like:
if ('places' = $post_type) {
$meta_query = array(
array(
'key' => 'place',
'value' => $post_id,
'compare' => 'LIKE'
)
);
$args['meta_query'] = $meta_query;
}
I tried global $typenow
but it didn’t do it.
My other option is to create additional field groups…
yes, of course!
It was that simple and right in front of me – feeling a bit silly now.
Thanks!!
The topic ‘Filter relationship field of post type’ is closed to new replies.
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.