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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.