Developer // ACF: Counting Repeater Rows Inside Flexible Content

So I was trying to count the number of repeater rows for a ACF repeater field in my WordPress theme, something which I figured would be a simple use of the count() function on the returned field.

In turns out though, that the following code doesn’t work with a repeater field if it is part of a flexible content block.

<?php
if(have_rows('card')):
$cards = get_sub_field('card');
$number_of_cards = count($cards);
endif;

Strange because you’d think checking a repeater field had rows before you tried to count them would be the correct order to go about it, and this is the suggested way of counting repeater field rows on the ACF site.

But in order to get this to work within flexible content you have to move the retrieval of the field to before the function checking if the repeater had rows.

<?php
$cards = get_sub_field('card');
if(have_rows('card')):
$number_of_cards = count($cards);
endif;

An odd fix when you know the original code works fine normally, just a quirk of operating with ACF flexible content.

13 Replies to “Developer // ACF: Counting Repeater Rows Inside Flexible Content”

  1. This has helped me twice!
    I was having trouble with counting a repeater in an ACF Gutenberg block and remembered finding this post a while back. On a hunch I looked you up again and used this order of operations.
    This seems to also apply to ACF field groups registered to gutenberg blocks, just in case anyone finds this same problem.

  2. Thank you very much about this! Wandered several discussions to find a solution and this was finally the thing! Very strange behavior this ended up being.

Leave a Reply

Your email address will not be published. Required fields are marked *