Calculate the sum of certain the_sub_fields

I am trying to calculate the sum total from two custom sub-fields using ACF. The custom field is called ‘repeater’ and the sub-field is called ‘space_avail’. I’ve tried the code below but it just lists the numbers individually rather than adding them up to a total. Please help.

<?php 
  $total = 0;
  while(the_repeater_field('repeater' )): 
      the_sub_field('space_avail' );
      $total += get_sub_field('space_avail' );
  endwhile; 
  echo $total;
?>

3 Answers
3

<?php 
  $total = 0;
  while(the_repeater_field('repeater' )): 
      the_sub_field('space_avail' );
      $total += intval( get_sub_field('space_avail' ) );
  endwhile; 
  echo $total;
?>

Notice the intval. It tells php to consider the result as an number, not as a string

Leave a Comment