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;
?>
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;
?>
Share
Improve this question
edited Dec 18, 2012 at 18:33
fuxia♦
107k39 gold badges255 silver badges459 bronze badges
asked Dec 18, 2012 at 18:11
JohnJohn
211 silver badge2 bronze badges
3 Answers
Reset to default 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
Try this:
$total = 0;
while(have_rows('repeater')) : the_row();
$space_avail = (int)get_sub_field('space_avail');
$total += $space_avail;
endwhile;
echo $total;
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;
?>