I’m creating a progress indicator for projects using a repeater field. While I’m able to count the rows of the repeater field itself, I want to also count the number of rows that have a certain sub field value (i.e. projects marked ‘completed’), so I can then calculate a ‘progress percentage’.
Is it possible to count rows with the same sub field value outside the repeater loop?

The repeater field stores the values as a serialized array in the database so I don’t think it will be easy to get an exact count outside of the repeater loop. If you need discreet access to this data I would use the acf/update_value
and acf/delete_value
filters to maintain the counts in different meta fields.
$field_key = 'your field key'; // or use name, type, etc and the proper filters
// Run on field value update
add_filter( 'acf/update_value/key={$field_key}', function($values, $post_id, $field){
if ( $field['type'] == 'repeater' ){
// you might need to delete "old" value sums in the db that aren't on the current values
$sums = array();
foreach( $values as $value ){
if ( !isset( $sums[$value] ) ){
$sums[$value] = 1;
} else {
$sums[$value]++;
}
}
foreach( $sums as $value => $sum ){
// save the sum for each value in a different field
}
}
}, 20, 3 );
// Run when a value is deleted
add_filter( 'acf/delete_value/key={$field_key}', function($value, $post_id, $field){
// probably do the exact same thing as when a value is updated... recalculate the sum of each value
}, 20, 3 );
Hi jsilver, Thanks for your reply – I couldn’t get that working unfortunately, so I ended up adding the repeater loop with a counter to count all the rows with the required sub field value. Thanks again.
There isn’t a way to count how many sub fields have a specific value without looping over the repeater, or looping over something. A repeater will return a nested array of rows and you can loop over that.
$total = 0;
$repeater = get_field('repeater');
if ($repeater) {
foreach ($repeater as $row) {
if ($row['sub_field_name'] == 'the value your looking for') {
$total++;
}
}
}
echo $total,' rows of ',count($repeater),
' total rows have the value the value your looking for';