Support

Account

Home Forums General Issues query all CPTs that have more than one item in an ACF relationship field?

Solved

query all CPTs that have more than one item in an ACF relationship field?

  • Hi,

    Sorry if this is more a general WP_Query question, I’m not sure.

    I’d like to query my custom post type where it has more than one item attached in an ACF relationship field

    eg if my CPTs are Company and Employee, i want to query all Companies that have more than one Employee defined in the “employees” acf relationship field on the “Company” CPT.

    I’m wondering if it is simpler to update a hidden flag/field/taxonomy “has_multiple” during save post hook, as obviously it is inefficient to do sub-queries through every Company looking for the number of employees

    thanks
    J.

  • 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); 
    }
    
  • Hi John,

    thanks for the example. this is the approach I eventually thought would be the case. I was going to save a taxonomy to query on eg “has_multiple” but if i can do a query on all items where meta value related_employees_count > 1 , that would do it

    thanks again
    J.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘query all CPTs that have more than one item in an ACF relationship field?’ is closed to new replies.