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;
?>

Related posts

Leave a Reply

3 comments

  1. <?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

  2. Try this:

    $total = 0;
    while(have_rows('repeater')) : the_row();
        $space_avail = (int)get_sub_field('space_avail');
        $total += $space_avail;
    endwhile;
    
    echo $total;
    
  3. Remove:

    the_sub_field('space_avail' );
    

    This display’s the string values.

    acf documentation repeater fields

        // loop through the rows of data
    while ( have_rows('repeater_field_name') ) : the_row();
    
        // display a sub field value
        the_sub_field('sub_field_name');
    

    so final code should be:

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