Robert Robert - 6 months ago 120
MySQL Question

How to count the total number of rows in a ACF repeater output

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') ){
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!

Answer Source

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' ) );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download