Search code examples
wordpressrepeateradvanced-custom-fields

Wordpress ACF Repeater Field - Only pull in first 2 fields


Topic kinda says it all. I need to only pull in the first two fields of an ACF repeater field.

Here is what I am trying to use but it is obviously not right:

<?php $args = [ 'posts_per_page' => 2, 'order' => 'desc']; ?>
<?php $ar = new WP_Query( $args ); ?>

<?php if( $ar->have_rows('prodImgs') ): while ( $ar->have_rows('prodImgs') ) : $ar->the_row(); ?>

    <img src="<?php the_sub_field('prodImg'); ?>" alt="">

<?php endwhile; ?>
<?php endif; ?>

How am I supposed to do this?


Solution

  • <?php
    // check if the repeater has data
    if( have_rows('prodImgs') ) {
      //counter
      $i=0;
      //loop through the rows
      while( have_rows('prodImgs') ) {
      the_row();
      //check if 2 subfields have been shown
      if ( $i > 1 ) { break; }
      echo "<img src='" . get_sub_field('prodImg_sub') . "' alt='Lorem ipsum'>";
      $i++;
      }
    }
    ?>
    

    You are mixing apples and pears, WP_Query and ACF Repeater field. WP_Query returns the post data, whilst the ACF function have_rows( $repeater_field_name, $post_id ); checks whether there are any data in the custom field repeater that is on your page/post (or if you specify $post_id on the relevant post/page). More info at https://www.advancedcustomfields.com/resources/repeater/