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.

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

Leave a Reply

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