I'm using ACF to output images in an image carousel called Flickity. Flickity supports image srcset with lazy loading.
Here's my basic ACF markup which uses wp_get_attachment_image:
<?php
$image = get_field('image');
$size = 'gallery';
echo wp_get_attachment_image( $image, $size );
?>
This nicely outputs on the front end, like so:
<img
width="1164"
height="450"
src="image-1164x450.jpg"
srcset="
image.jpg 1164w,
image-300x116.jpg 300w,
image-768x297.jpg 768w,
image-1024x396.jpg 1024w,
image-2328x900.jpg 2328w,
image-1680x649.jpg 1680w,
image.jpg 3492w
"
sizes="(max-width: 1164px) 100vw, 1164px"
>
Flickity Docs specify that you should use data-flickity-lazyload-srcset
and data-flickity-lazyload-src
. This means changing the output on wp_get_attachment_image.
I've achieved this via functions.php, like so (source):
function gs_change_attachment_image_markup($attributes){
if (isset($attributes['src'])) {
$attributes['data-flickity-lazyload-src'] = $attributes['src'];
$attributes['src'] = '';
}
if (isset($attributes['srcset'])) {
$attributes['data-flickity-lazyload-srcset'] = $attributes['srcset'];
$attributes['srcset'] = '';
}
return $attributes;
}
add_filter( 'wp_get_attachment_image_attributes', 'gs_change_attachment_image_markup' );
This has worked perfectly on the frontend, like so:
<img
width="1164"
height="450"
srcset=""
data-flickity-lazyload-src="image-1164x450.jpg"
data-flickity-lazyload-srcset="
image.jpg 1164w,
image-300x116.jpg 300w,
image-768x297.jpg 768w,
image-1024x396.jpg 1024w,
image-2328x900.jpg 2328w,
image-1680x649.jpg 1680w,
image.jpg 3492w
"
sizes="(max-width: 1164px) 100vw, 1164px"
>
Unfortunately, this breaks the images on other custom or native fields using wp_get_attachment_image.
Is it possible to assign gs_change_attachment_image_markup
function to a specific custom field so it's not being applied site wide?