最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

custom field - Calculate the sum of certain the_sub_fields

programmeradmin1浏览0评论

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
Add a comment  | 

3 Answers 3

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;
?>
发布评论

评论列表(0)

  1. 暂无评论