Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 664
Robert Avatar asked May 04 '17 16:05

Robert


People also ask

How many rows does an ACF repeater have?

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.

What is repeater in ACF?

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!

How do you get group fields in ACF?

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.


2 Answers

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' ) );
like image 139
Robert Avatar answered Sep 22 '22 06:09

Robert


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;
like image 35
Otis Feru Avatar answered Sep 23 '22 06:09

Otis Feru