Support

Account

Home Forums Add-ons Repeater Field looping nested repeaters

Solved

looping nested repeaters

  • Hi, I am trying to loop thru two nested repeaters to get the total number of items they contain. I am getting int(0) NULL or string(1) “0”.

    ACF:
    -collections (repeater)
    –name
    –banners (repeater)
    —banner_type

    In the front end I do have 2 collections with 3 items each.
    in the previous page/parent I wanna output 6 items.

    I m trying to do it like that but with no success.

    $number_of_banners = 0;
    $collections = get_field(‘collections’);

    foreach( $collections as $collection) {
    $banners = get_sub_field(‘banners’);
    $number_of_banners = $number_of_banners + $banners.count();
    };

    var_dump($number_of_banners);

    Thanks for any help.

  • the first problem I see is that you are trying to use get_sub_field() outside of a have_rows() loop.

    correct loop using have_rows()

    
    if (have_rows('collections')) {
      while (have_rows('collections')) {
        the_row();
        $banners = get_sub_field('banners');
      }
    }
    

    correct loop using array

    
    $collections = get_field('collections');
    foreach ($collections as $collection) {
      $banners = $collection['banners'];
    }
    

    The other thing is this $banners.count(); should be count($banners)

  • Thank you John,
    I solved it using the loop have rows:

    $number_of_banners = 0;
    if( have_rows('collections') ):
    	while ( have_rows('collections') ) : the_row();
    		if( have_rows('banners') ):
    			while ( have_rows('banners') ) : the_row();
    				$number_of_banners +=1;
    			endwhile;
    		endif;
    	endwhile;
    endif;
    
    <p><?= $number_of_banners === 1 ? $number_of_banners . " banner" : $number_of_banners . " banners" ?></p>
    

    I tried with the correct loop using array and it return 5 instead of 8 which is the number of only 1 banner repeater.
    This is solved, however I would like to improve it using the loop array.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘looping nested repeaters’ is closed to new replies.