Lisa Jaffé Lisa Jaffé - 1 month ago 9
PHP Question

Adding simple counter variable to my ACF Repeater loop

I am trying to add a simple counter variable to my ACF Repeater loop for an accordion but am getting an error. Can anyone offer some assistance? Thanks!

<?php
$counter = 0; if( have_rows('faq') ):$counter++; ?>


<section class="ac-container">

<?php while( have_rows('faq') ): the_row();

$question = get_sub_field('faq_question');
$answer = get_sub_field('faq_answer');
?>



<div>
<input id="ac-<?php echo $counter;?>" name="accordion-1" type="radio" checked />
<label for="ac-<?php echo $counter;?>"><?php echo $question; ?></label>
<article class="ac-small"><?php echo $answer; ?></article>
</div>


<?php endwhile; ?>

</section>

<?php endif; ?>

Answer

Tray like this

<?php
        if( have_rows('faq') ):$counter = 0;?>
            <section class="ac-container">
                <?php while( have_rows('faq') ): the_row();
                    $question = get_sub_field('faq_question');
                    $answer = get_sub_field('faq_answer');
                    ?>
                    <div>
                        <input id="ac-<?php echo $counter;?>" name="accordion-1" type="radio" checked />
                        <label for="ac-<?php echo $counter;?>"><?php echo $question; ?></label>
                        <article class="ac-small"><?php echo $answer; ?></article>
                    </div>
                    <?php $counter++; endwhile; ?>

            </section>
        <?php endif; ?>