agon024
agon024

Reputation: 1007

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?

Upvotes: 0

Views: 1637

Answers (2)

crs1138
crs1138

Reputation: 946

<?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/

Upvotes: 2

Anthony Hubble
Anthony Hubble

Reputation: 63

<?php $rows = get_field('prodImgs'); ?>

<?php $i = 0; if ($rows):?>

    <?php foreach($rows as $row): ?>

        <img src="<?php echo $rows[$i][/* name of first field */]; ?>" alt="">
        <?php echo $rows[$i][/* name of Second field */]; ?>

    <?php $i++; endforeach; ?>

<?php endif; ?>

Upvotes: 0

Related Questions