How To Use srcset Within WordPress

With my custom WordPress themes, I add default image sizes to be used throughout the site for responsive design.

 

Since v4.4, WordPress has natively allowed the use of srcset, which enables your browser to select the right image and pull it down from the WordPress media library.

 

With the uptake in retina devices, I set the following in functions.php by default, so when an image is uploaded, WordPress will create different sized versions automatically.

 

update_option('medium_size_w', 768);
update_option('medium_size_h', 768);
update_option('large_size_w', 990);
update_option('large_size_h', 990);
add_image_size('full_col', 1200, 1200 );
add_image_size('full_col_ret', 2400, 2400 );

 

I use 1200px as generally the central column width is 1200px max-width and 2400px, for full width retina screens (column width x2). You should adjust these values depending on your site and add more options if required.

 

To call an post thumbnail image using srcset, use the following PHP snippet:

 

echo wp_get_attachment_image( get_post_thumbnail_id(), 'large');

 

The srcset code can be adjusted easily for use with plugins such as ACF, like so:

 

echo wp_get_attachment_image( get_field('my_image'), 'large');

 

If you now view your image source (or the image source of this page), you will see an srcset array of images each with their own preset width of use, ready for the browser.

 

Images added directly into the WYSIWYG editor, will use srcset by default. This tutorial is helpful for building static layouts.

Leave a Reply