Search code examples
phpwordpressrepeateradvanced-custom-fields

Wordpress acf repeater get first and second images only


I'm using acf plugin on a wordpress site. I am using a repeater field with an image subfield that is displayed on a blogpost. My goal is to only get and display the first and second images from a blog post to be displayed for the homepage.

I tried using this code from the acf site documentation but to no avail the code is not working. Can someone know the issue?

         <?php while ($the_query -> have_posts()) : $the_query ->
            the_post(); 
            $postqID = get_the_ID();
          ?>

          <?php

          $rows = get_field('post_images', $postqID ); // get all the rows
          $first_row = $rows[0]; // get the first row
          $first_row_image = $first_row['post_image' ]; // get the sub field value 

          // Note
          // $first_row_image = 123 (image ID)

          $image = wp_get_attachment_image_src( $first_row_image, 'full' );
          // url = $image[0];
          // width = $image[1];
          // height = $image[2];
          ?>
          <img src="<?php echo $image[0]; ?>" />

Solution

  • I just solved this issue. For those who are also having issues on displaying certain number of rows of images on a repeater field. You can refer my answer. The code below returns two images from a repeater field. Just changed the condition ($i>1), if you wish to return certain number of image.

              <?php
    
              $i = 0;
              if(get_field('post_images', $postqID)):
              ?>
                <?php while (has_sub_field('post_images',$postqID)): ?>
    
                  <img src="<?php the_sub_field('post_image')['url']; ?>"></img>
    
                <?php
    
                  $i++;
                  if($i > 1)
                  {
                    break;
                  }
                ?>
                <?php  endwhile; ?>
              <?php endif; ?>