Support

Account

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); 
    }