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

Robert picture Robert · May 4, 2017 · Viewed 24k times · Source

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!

Answer

Robert picture Robert · May 4, 2017

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' ) );