Responsive Images in WordPress with ACF
Use ACF with the responsive image features found in WordPress core!
Use ACF with the responsive image features found in WordPress core!
WordPress 4.4 shipped with an awesome new feature, Responsive Images. This feature works great for any images within the standard WYSIWYG editor. The srcset and sizes attributes are added to each img tag to inform the browser of the available sizes for each image.
However, If you’re using Advanced Custom Fields to store and display images within a custom theme you might need to modify your themes to use this new feature. I’ve coded up a simple helper function to make this a little easier.
You can add this function to your themes functions.php file or a functionality plugin:
To use this within your custom theme, open an image tag, call the function and pass 3 parameters:
-
The
image ID(I’m getting this from an ACF image field which returns an ID) -
The
image size(I’ve used a custom image size, added via the add_image_size ) -
The
max width(In this case the max width this image is 640px)
It will return the src, srcset and sizes attributes, you can assign your class and alt text as needed, see this example:
This will generate the responsive images markup, for all of the image sizes you have set (that have the same aspect ratio), similar to this:
Bonus Tip:
In WordPress 4.4 max srcset size is set to 1600px wide by default, if you have images larger than that size that you’d like included in the srcset you can use this filter: