Responsive Images feature in WordPress

Do you have WordPress 4.4+ installed? All new images inserted in posts after the WP upgrade have scrset attribute then.

How scrset and sizes attributes work?

srcset ands sizes attributes contain the information to help browser decide which image size/file is the best.

<img src="image.jpg" srcset="image-300x188.jpg 300w, image-700x600.jpg 700w, image-1024x640.jpg 1024w, image-1200x750.jpg 1200w" sizes="(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px">

What does it mean?

It was described great in CSS-Tricks screencast here.

As for me, I would like to talk about WordPress.

Responsive images — WordPress 4.4 new feature

WordPress is using the_content to add the responsive attributes to your uploaded images:

How to ask WordPress not to add responsive attributes to all content images

There are two ways — you can remove wp-image-{ATTACHMENT_ID} class from specific attachments or disable responsive images globally by adding this to your theme functions.php.

remove_filter( 'the_content', 'wp_make_content_images_responsive' );

How to add scrset and sizes attributes to WordPress attachments in the code.

<img src="<?php echo wp_get_attachment_image_url( $attachment_id, 'medium' ) ?>"
     srcset="<?php echo wp_get_attachment_image_srcset( $attachment_id, 'medium' ) ?>"
     sizes="<?php echo wp_get_attachment_image_sizes( $attachment_id, 'medium' ) ?>" />

Let’s look at each function separately.

How to use images with different ratio for mobile devices

Look at the picture below. Which image do you think looks better on this iPhone 5?

responsive-images-wordpress

You may notice that image ratio (width/height) differs, so, WordPress wouldn’t add the right image size to scrset attribute. How to force it to do it:

function misha_sources( $sources, $size_array, $image_src, $image_meta, $attachment_id ){
	/*
	 * Your variables here
	 */
	$image_size_name = 'square500'; // add_image_size('square500', 500, 500, true);
	$breakpoint = 500;
 
	$upload_dir = wp_upload_dir();
 
	$img_url = $upload_dir['baseurl'] . '/' . str_replace( basename( $image_meta['file'] ), $image_meta['sizes'][$image_size_name]['file'], $image_meta['file'] );
 
	$sources[ $breakpoint ] = array(
		'url'        => $img_url,
		'descriptor' => 'w',
		'value'      => $breakpoint,
	);
	return $sources;
}
 
add_filter('wp_calculate_image_srcset','misha_sources',10,5);

For better user experience you can use the Manual Image Crop plugin to crop image the way you want.

You can use Manual Image Crop plugin to crop the resized image the way you want.
Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X