Support

Account

Home Forums ACF PRO Get total number from multiple post object fields Reply To: Get total number from multiple post object fields

  • @hube2 You were right – my empty fields were returning false. I was able to use your method of validating with some slight tweaks to work for my specific case.

    Here’s the solution that ended up working for me:

    $instructors_total = 0;
    $instructors = get_field('instructors');
    if (is_array($instructors)) {
      $instructors_total = count($instructors);
    }
    $leaders_total = 0;
    $leaders = get_field('leaders');
    if (is_array($leaders)) {
      $leaders_total = count($leaders);
    }
    $designers_total = 0;
    $designers = get_field('designers');
    if (is_array($designers)) {
      $designers_total = count($designers);
    }
    $speakers_total = 0;
    $speakers = get_field('speakers');
    if (is_array($speakers)) {
      $speakers_total = count($speakers);
    }
    $staff_total = $instructors_total + $leaders_total + $designers_total + $speakers_total;

    This is based on both of @hube2‘s recommendations except that I’m using count() inside my is_array() validations rather than outside of them. Using count() to add the totals together outside the validation was returning a ‘1’ even if the array was empty. So if all of my arrays were empty, I was still getting ‘4’. I’m not entirely sure why.

    There might be a better way to do this, but this is working well for me.

    Thanks again @hube2!