Responsive images in WordPress with srcset

Published March 7, 2019
.* :☆゚

WordPress supports the srcset feature out of the box, and alongside it’s image thumbnail generation is extremely useful for optimising a site that serves a lot of images, especially those involving huge full width panels. In fact, now I almost exclusively use srcset for all images loaded on a page.

All you need is the image attachent ID, and WordPress will take care of the rest for you.

<?php
    $id = get_post_thumbnail_id();
    $size = 'medium';
    $img_src = wp_get_attachment_image_url( $id, $size );
    $img_srcset = wp_get_attachment_image_srcset( $id, $size );
    $title = get_post($id)->post_title;
    $alt = get_post_meta($id, '_wp_attachment_image_alt')[0]) ?: $title;
    ?>
<img src="<?php echo esc_url( $img_src ); ?>"
    srcset="<?php echo esc_url( $img_srcset ); ?>"
    sizes="(min-width: 768px) 500px, 100vw"
    alt="<?php esc_attr_e($alt); ?>"
    title="<?php esc_attr_e($title); ?>"
    class="featured-image">

Using this tag will generate markup that looks a little like this:

<img 
src="https://blueroom.org.au/wp-content/uploads/2019/03/Winter-Nights-Application-Open-1200x675.jpg"
srcset="https://blueroom.org.au/wp-content/uploads/2019/03/Winter-Nights-Application-Open-1200x675.jpg 1200w,
https://blueroom.org.au/wp-content/uploads/2019/03/Winter-Nights-Application-Open-150x84.jpg 150w,
https://blueroom.org.au/wp-content/uploads/2019/03/Winter-Nights-Application-Open-600x338.jpg 600w,
https://blueroom.org.au/wp-content/uploads/2019/03/Winter-Nights-Application-Open-768x432.jpg 768w"
sizes="(min-width: 768px) 1200px, 100vw"
alt=""
title=""
class="image">

Note: this snippet checks if an alt tag is set on the image. If there isn’t an alt tag to be found(it is blank by default), it falls back to the image’s title. Whether these fields are filled out are up to you/your client, but it is important to remember, alt tags are important, and having a blank alt tag is better than nothing at all.


Use srcset with ACF

To use this tag with ACF, you just have to set your custom field to return the ID instead of the object, then you can use it in place of the thumbnail ID like below:

<?php
    $id = get_field('secondary_image');
    $size = 'medium';
    $img_src = wp_get_attachment_image_url( $id, $size );
    $img_srcset = wp_get_attachment_image_srcset( $id, $size );
    $title = get_post($id)->post_title;
    $alt = get_post_meta($id, '_wp_attachment_image_alt')[0]) ?: $title;
    ?>
<img src="<?php echo esc_url( $img_src ); ?>"
    srcset="<?php echo esc_url( $img_srcset ); ?>"
    sizes="(min-width: 768px) 500px, 100vw"
    alt="<?php esc_attr_e($alt); ?>"
    title="<?php esc_attr_e($title); ?>"
    class="featured-image">

The long of it

Read more about using srcset in WordPress