Home › Forums › Add-ons › Repeater Field › access array of repeater fields by index
Hey everyone,
I have a repeater field of 12 images, i am now trying to use the code below to access only the first 4, then later on 4-8, then 9-12,
how can i achieve this by editing the code below?
<?php if( have_rows('repeater_field_name') ): ?>
<ul>
<?php while( have_rows('repeater_field_name') ): the_row(); ?>
<li>sub_field_1 = <?php the_sub_field('sub_field_1'); ?>, sub_field_2 = <?php the_sub_field('sub_field_2'); ?>, etc</li>
<?php
$sub_field_3 = get_sub_field('sub_field_3');
// do something with $sub_field_3
?>
<?php endwhile; ?>
</ul>
<?php endif; ?>
Thanks for any suggestions!
Hi @khadesa
The easiest way would be something like this:
<?php if( have_rows('repeater_field_name') ): ?>
<ul>
<?php $i = 1; ?>
<?php while( have_rows('repeater_field_name') ): the_row(); ?>
<?php if($i <= 4 ){ ?>
<li>sub_field_1 = <?php the_sub_field('sub_field_1'); ?>, sub_field_2 = <?php the_sub_field('sub_field_2'); ?>, etc</li>
<?php
$sub_field_3 = get_sub_field('sub_field_3');
// do something with $sub_field_3
?>
<?php } ?>
$i++;
<?php endwhile; ?>
<?php $i = 1; ?>
<?php while( have_rows('repeater_field_name') ): the_row(); ?>
<?php if($i >= 5 && $i <= 8 ){ ?>
<li>sub_field_1 = <?php the_sub_field('sub_field_1'); ?>, sub_field_2 = <?php the_sub_field('sub_field_2'); ?>, etc</li>
<?php
$sub_field_3 = get_sub_field('sub_field_3');
// do something with $sub_field_3
?>
<?php } ?>
$i++;
<?php endwhile; ?>
<?php $i = 1; ?>
<?php while( have_rows('repeater_field_name') ): the_row(); ?>
<?php if($i >= 9 ){ ?>
<li>sub_field_1 = <?php the_sub_field('sub_field_1'); ?>, sub_field_2 = <?php the_sub_field('sub_field_2'); ?>, etc</li>
<?php
$sub_field_3 = get_sub_field('sub_field_3');
// do something with $sub_field_3
?>
<?php } ?>
$i++;
<?php endwhile; ?>
</ul>
<?php endif; ?>
You can also get the repeater and store it in a variable first like this:
$repeater = get_field('repeater_field_name');
Then you can loop it using foreach.
I hope this helps.
You must be logged in to reply to this topic.
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!
Are you building WordPress sites with ACF and @BeaverBuilder, and wanted to use your ACF Blocks in both the block editor and Beaver Builder?
— Advanced Custom Fields (@wp_acf) May 10, 2023
The BB team recently added support for using ACF Blocks in Beaver Builder. Check it out 👇https://t.co/UalEIa5aQi
© 2023 Advanced Custom Fields.
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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.