Last active
June 27, 2024 13:19
-
-
Save 8ctopotamus/0ae8c9a9753ad406fa6d60d8008e0013 to your computer and use it in GitHub Desktop.
Count number of repeater fields in ACF flexible content.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. |
👏🏼
You're a saviour! Thank you 🔥
Thanks this caught me up today.
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
wish I would have found this before I spent 3 hours trying to figure this out.