Support

Account

Home Forums Add-ons Gallery Field Return all images in a loop Reply To: Return all images in a loop

  • First of all, you can’t use return inside a foreach loop. Second of all, your code is wrong. The function you are using to retrieve images is already echoing on your behalf.

    If you’d like to output the HTML attachment element then you can either get rid of the return keyword or use a different function to first retrieve the url of the image and then echo it yourself as an image.

    See: https://developer.wordpress.org/reference/functions/wp_get_attachment_image/

    Here’s an example for the first method:

    
    $images = get_field('images');
    $size = 'large'; // (thumbnail, medium, large, full or custom size)
    if( $images ){
       foreach( $images as $image_id ){
          wp_get_attachment_image( $image_id, $size );
       }
    }
    

    See: https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/
    And here’s an example for the second method:

    $images = get_field('images');
    $size = 'large'; // (thumbnail, medium, large, full or custom size)
    if( $images ){
       foreach( $images as $image_id ){
          $image_url = wp_get_attachment_image_url( $image_id, $size );
          echo "<img src='$image_url' "/>;
       }
    }