How to use the responsive images feature from WP 4.4 in your themes

Following our exchange in the comments I’ve reread your question and have a pretty straightforward answer:

It looks like it’s working fine.

You are worried about the sizes attribute in your second example, but it’s the srcset attribute that you should look at and it is showing all of your image sizes:

<img 

src="http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg" 

class="attachment-full size-full" alt="Delft_IMG_6275" 

srcset="http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922.jpg 1920w,
http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-300x70.jpg 300w,
http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-768x180.jpg 768w,
http://xxx.dev/wp-content/uploads/Delft_IMG_6275-e1453192498922-1024x241.jpg 1024w"

sizes="(max-width: 1920px) 100vw, 1920px"

height="451" width="1920">

Your browser reads the attributes like this:

1 – Look at the sizes attribute and find the first match for the current viewport width. In this case, if the viewport is anything up to 1920px wide, then use the 100vw value, converted to px, otherwise use 1920px.

2 – Look at the srcset attribute and choose an image that fits the value from (1).

On a nice big screen with a full width window the browser chooses the sizes value of 1920px. This points the browser to the image marked with 1920w in the srcset attribute, with the URL of your full size image.

On a portrait iPad, where the viewport is 768px wide, the value obtained in (1) will be 100vw which for this viewport is 768px. Looking in the srcset for 768w we get the URL to the medium_large image size (a new default size in WP4.4 which doesn’t show in the admin interface).

When there’s no exact match for the viewport width, the browser should choose the next size up.

Now, there are circumstances where you might want to supply a longer list of images which you can add using add_image_size() in your theme. WP will build a srcset attribute using all the images that match the aspect ratio of the image size you choose to display.

There are also circumstances where you want a custom sizes attribute and you can filter the attribute for that, but as your question stands I don’t think that’s what you’re after.

Leave a Comment