Question: How do you simply count the rows in the output of an ACF repeater field?
Goal: to make the output look different with a css class when there's only one row, vs. more than one row.
My code:
if( have_rows('testimonials')) {
$counter = 0;
$numtestimonials = '';
//loop thru the rows
while ( have_rows('testimonials') ){
the_row();
$counter++;
if ($counter < 2) {
$numtestimonials = 'onlyone';
}
echo '<div class="testimonial ' . $numtestimonials . '">';
// bunch of output here
echo '</div>';
}
}
Obviously, The way I do it here will not work as the count is < 2 the first time thru the row, so it returns true even if more rows are counted after.
Thank you!
The index returned from this function begins at 1. This means a Repeater field with 3 rows of data will produce indexes of 1, 2 and 3.
The repeater field allows you to create a set of sub fields which can be repeated again and again whilst editing content! Any type of field can be added as a sub field which allows you to create and manage very customized data with ease!
To create subfields inside the Group, click on the Add Field button and start adding fields. Since here I am creating an ACF Group for the hero section, so I have added four subfields like Image, Title, Description, and a button. It's totally up to you what fields you want to add.
OK, I finally found the answer to this.
The way to count total rows in an ACF repeater is:
$numrows = count( get_sub_field( 'field_name' ) );
It's work for me, count must be placed before if(have_rows('repeater_field') :
Ternary operator to avoid warning errors if repeater is empty
If you place the count after "if(have_rows('repeater_field')) :", count returns FALSE
$repeater_field = get_sub_field('repeater_field');
// OR if repeater isn't a sub_field
// $repeater_field = get_field('repeater_field');
// ternary operator to avoid warning errors if no result
$count = $repeater_field ? count($repeater_field) : FALSE;
if(have_rows('repeater_field')) : // OR if($count) :
echo 'Number of posts:' . $count . '<br>';
while(have_rows('repeater_field')) : the_row();
echo get_sub_field('field_name') . '<br>';
endwhile;
endif;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With