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.
Thank you so much for this tip Katie! My code will be very good and short thanks to you 🙂
No problem Tom, glad it helped 🙂
Thank you! I was searching high and low for this and couldn’t find any information – works perfectly.
Thank you, this had me scratching my head for quite some time!
I was similarly confused! Happy it helped
Katie, thank you so much. I was figuratively banging my head against my desk like wtf.
No problem, glad it wasn’t just me who struggled with it!
Thank you for sharing this Katie.. it helped me out with a deadline 🙂
Thank you! Was just scratching my head with this one and your post gave me the answer. Very odd issue.
Saved my night. Thanks for sharing I would never try to move this out before checking if (have_rows)
Phew! Thanks for posting
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.
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.