Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 8ctopotamus/0ae8c9a9753ad406fa6d60d8008e0013 to your computer and use it in GitHub Desktop.
Save 8ctopotamus/0ae8c9a9753ad406fa6d60d8008e0013 to your computer and use it in GitHub Desktop.
Count number of repeater fields in ACF flexible content.
// Source: https://katienelson.co.uk/developer-acf-counting-repeater-rows-inside-flexible-content/
// 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 now the original code works fine normally, just a quirk of operating with ACF flexible content.
@pirco
Copy link

pirco commented Feb 14, 2021

wish I would have found this before I spent 3 hours trying to figure this out.

@jonathanemiranda
Copy link

👏🏼

@zakariaelk
Copy link

You're a saviour! Thank you 🔥

@mattkeys
Copy link

Thanks this caught me up today.

@8ctopotamus
Copy link
Author

8ctopotamus commented Jun 23, 2022

Glad people are finding this useful! Just wanted to point out that I am not the original author of this handy snippet... I just noted it down as a gist for my own future reference. 👏 Props go to @katienelson 👏 (source in comment at top of file)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment