Display an ACF Gallery Field as a Responsive Image Grid

Loop through a gallery field and output responsive images with srcset using wp_get_attachment_image().

php field-types
|

Loop through a gallery field and output responsive images with srcset using wp_get_attachment_image().

Set the gallery field’s return format to Image Array, then loop through the images:

<?php
$gallery = get_field( 'photo_gallery' );

if ( $gallery ) : ?>
    <div class="gallery-grid">
        <?php foreach ( $gallery as $image ) : ?>
            <figure>
                <?php echo wp_get_attachment_image( $image['ID'], 'medium', false, [
                    'class'   => 'gallery-image',
                    'loading' => 'lazy',
                ] ); ?>
                <?php if ( $image['caption'] ) : ?>
                    <figcaption><?php echo esc_html( $image['caption'] ); ?></figcaption>
                <?php endif; ?>
            </figure>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

If your return format is Image ID, the loop is simpler:

<?php
$gallery = get_field( 'photo_gallery' );

if ( $gallery ) : ?>
    <div class="gallery-grid">
        <?php foreach ( $gallery as $image_id ) : ?>
            <?php echo wp_get_attachment_image( $image_id, 'medium', false, [
                'class'   => 'gallery-image',
                'loading' => 'lazy',
            ] ); ?>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

Basic CSS grid for the gallery:

.gallery-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 1rem;
}

.gallery-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 0.5rem;
}

Using wp_get_attachment_image() provides automatic srcset and sizes attributes for responsive image loading.

Related Snippets

Stay Updated

Get ACF tips and new extensions in your inbox

No spam. Unsubscribe anytime.