Home › Forums › General Issues › query all CPTs that have more than one item in an ACF relationship field? › Reply To: query all CPTs that have more than one item in an ACF relationship field?
Since the relationship field stores a serialized array holding the ID values of each related post, you’re correct, it would be virtually impossible to do a query based on this value. It would be much easier to create an acf/save_post filter that gets the of related posts and sets that number into another “hidden” post meta field. It doesn’t really need to be hidden, just an extra field outside of ACF. Something like:
add_action('acf/save_post', 'count_related_employees', 20); //run after acf
function count_related_employees($post_id) {
if (get_post_type($post_id) != 'company') {
return;
}
// 3rd parameter: false: gets value without formatting
$employees = count(get_field('related_employees', $post_id, false));
update_post_meta($post_id, 'related_employees_count', $employees);
}
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.