If you need to calculate values across repeater field rows, you need to use a PHP-based calculation handler to process the repeater rows to suit your needs.
Note: it is not currently possible to use calculated fields inside a repeater.
In the following example, a simple repeater with name data_rows has been used with one sub field named number. The calculated field is named total. The snippet hooks into the calculated field to work out the total of all number fields across all rows in the repeater.
<?php // The field name of the calculated field in this example is 'total' $calculated_field_name = 'total'; // Use a PHP filter to calculate the value of the calculated field based on values inside a repeater. add_filter( 'af/field/calculate_value/name=' . $calculated_field_name, function () { // Initialise the total. $sum = 0; // Get the value of the repeater field. This will be a multidimensional array of rows and sub fields. $repeater_rows = af_get_field( 'data_rows' ); // If the repeater has rows in it, loop through the rows if ( is_array( $repeater_rows ) ) { foreach ( $repeater_rows as $row ) { // The sub field name of the number field in this example is 'number' $sub_field_name = 'number'; // Get the value of the sub field from the row $sub_field_value = $row[ $sub_field_name ]; // Skip empty values – this is important to avoid PHP warnings if ( empty( $sub_field_value ) ) { continue; } // Add the value to the total $sum += $sub_field_value; } } // Return the desired output to be displayed in the form where the calculated field is used. return 'The total is: ' . $sum; }, 10, 0 );
Was this article helpful?
That’s Great!
Thank you for your feedback
Sorry! We couldn't be helpful
Thank you for your feedback
Feedback sent
We appreciate your effort and will try to fix the article