# ACF Gallery Field as a Responsive Grid

> Adds an [acf_gallery name="gallery"] shortcode that shows an ACF gallery field as a lazy-loaded, responsive image grid linking to the full-size files.

- Type: PHP
- Runs: Run everywhere
- Category: [Custom Post Types & Fields](https://wpide.com/library/category/post-types/)
- Tags: acf, gallery, shortcode
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/acf-gallery-grid-shortcode/

## Code

```php
add_shortcode( 'acf_gallery', function ( $atts ) {
    $atts    = shortcode_atts( array( 'name' => 'gallery', 'columns' => 3, 'size' => 'medium_large', 'post_id' => 0 ), $atts, 'acf_gallery' );
    $post_id = $atts['post_id'] ? absint( $atts['post_id'] ) : get_the_ID();

    if ( ! $post_id || ! function_exists( 'get_field' ) || ! is_post_publicly_viewable( $post_id ) ) {
        return '';
    }

    $ids = get_field( sanitize_key( $atts['name'] ), $post_id, false ); // Raw value: attachment IDs.
    $ids = array_filter( array_map( 'absint', is_array( $ids ) ? $ids : explode( ',', (string) $ids ) ) );

    if ( ! $ids ) {
        return '';
    }

    $cols = min( 6, max( 1, absint( $atts['columns'] ) ) );
    $html = '<div class="acf-gallery-grid" style="display:grid;gap:12px;grid-template-columns:repeat(auto-fill,minmax(min(100%,' . (int) floor( 960 / $cols ) . 'px),1fr))">';

    foreach ( $ids as $id ) {
        $full = wp_get_attachment_image_url( $id, 'full' );

        if ( $full ) {
            $html .= '<a href="' . esc_url( $full ) . '">' . wp_get_attachment_image( $id, sanitize_key( $atts['size'] ), false, array( 'loading' => 'lazy', 'style' => 'width:100%;height:auto;display:block' ) ) . '</a>';
        }
    }

    return $html . '</div>';
} );
```

## Notes

Gallery fields need ACF PRO. Set columns="4" for a wider grid; on phones it drops to two columns.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "ACF Gallery Field as a Responsive Grid" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
