Home › Forums › General Issues › Getting a count of repeater sub fields
Hi,
I am trying to get a count of repeater sub fields e.g.
<?php if( have_rows('questions') ): ?>
<ul class="questions-answers">
<?php while( have_rows('questions') ): the_row(); ?>
<li><h3><a href="#"><?php the_sub_field('question_text'); ?></a></h3>
<p><?php the_sub_field('answer_text'); ?></p></li>
<?php endwhile; ?>
</ul>
is what I have now. I’d like to add a dynamically assigned class to the p element e.g.
<p class="class_<?php $the_sub_field('number'); ?>"><?php the_sub_field('answer_text'); ?></p>
The code might be different to what I’ve posted but basically this is what I need. Any help gratefully received.
Something like this? 🙂
<?php if( have_rows('questions') ): ?>
<?php $counter = 1; //this sets up the counter starting at 0 ?>
<ul class="questions-answers">
<?php while( have_rows('questions') ): the_row(); ?>
<li><h3><a href="#"><?php the_sub_field('question_text'); ?></a></h3>
<p class="class_<?php echo $counter; // Prints the number of counted row ?>"><?php the_sub_field('answer_text'); ?></p>
<p><?php the_sub_field('answer_text'); ?></p></li>
<?php $counter++; // add one per row ?>
<?php endwhile; ?>
</ul>
<?php endif; ?>
Or if you want to know the count before running through the array, try something like:
if( have_rows('questions') ):
$my_fields = get_field_object('questions');
$count = (count($my_fields['value']));
endif;
I’m trying to echo the count of the rows, but it keeps returning zero. Here is my code:
<?php if( have_rows('repeater_name') ):
$my_fields = get_field_object('repeater_name');
$count = (count($my_fields['value']));
echo $count;
endif;?>
I have 3 repeater rows but it keeps returning “0”. Any idea why?
@nicholaspetersen Try just counting $my_fields instead of $my_fields[‘value’].
The topic ‘Getting a count of repeater sub fields’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.