ACF: Repeater Fields
Below is my Advanced Custom Fields (ACF) cheatsheet for repeater fields.
***This is a work in progress.
Basic Usage:
In the basic usage we need to check if the repeater exists and has fields.
Then we get the sub field values.
<?php if ( have_rows('repeater_field') ): ?> <?php while ( have_rows('repeater_field') ) : the_row(); $sub1 = get_sub_field('sub_field_1'); $sub2 = get_sub_field('sub_field_2'); ?> <div><?php echo $sub1 ?></div> <div><?php echo $sub2 ?></div> <?php endwhile; ?> <?php endif; ?>
Outside the Loop:
We use this when we want the repeater outside WordPress’s the_post();
loop or query.
When we know the post or page ID
<?php if ( have_rows('repeater_field', 123) ): ?> <?php while ( have_rows('repeater_field', 123) ) : the_row(); $sub1 = get_sub_field('sub_field_1'); ?> <div><?php echo $sub2 ?></div> <?php endwhile; ?> <?php endif; ?>
When we don’t know the post or page ID but we are on the correct page.
global $post;
gets the post or page ID outside the loop.
<?php global $post; ?> <?php if ( have_rows('repeater_field', $post->ID ) ): ?> <?php while ( have_rows('repeater_field', $post->ID) ) : the_row(); $sub1 = get_sub_field('sub_field_1'); ?> <div><?php echo $sub2 ?></div> <?php endwhile; ?> <?php endif; ?>
Getting fields from the Options Page
<?php if ( have_rows('repeater_field', 'option') ): ?> <?php while ( have_rows('repeater_field', 'option') ) : the_row(); $sub1 = get_sub_field('sub_field_1'); $sub2 = get_sub_field('sub_field_2'); ?> <div><?php echo $sub1 ?></div> <div><?php echo $sub2 ?></div> <?php endwhile; ?> <?php endif; ?>
Get only the 1st Row:
Skip the 1st Row:
Display random Rows:
Get from a Category or Taxonomy:
Get Even / Odd rows:
Even / Odd is very handy for adding CSS classes to the fields.
if ( get_row_index() % 2 == 0 ) : $class = 'class="promo_item pb'. $pbox .'"'; $overlay = '<div class="overlay" style="background-image: url('. $img['sizes']['Promo'] .')"></div>'; else : $class = 'class="promo_item green pb'. $pbox .'"'; $overlay = '<div class="overlay" style="background-image: url('. $img['sizes']['Promo'] .')"></div>'; endif;