Support

Account

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

Helping

Return all images in a loop

  • Hello. How can we use the ‘return’ in a loop and not use the ‘echo’? We can use the return but it only return one image and not all.
    ORIGINAL

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

    What we wanted to do

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

    We need to use the return because of conflict with other plugins and not echo.

  • 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' "/>;
       }
    }
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.