New Responsive Images in WordPress 4.4 and How to Adjust Them to a Theme.

Since WP version 4.4, if you look into source of your images in i.e. WordPress gallery, you’ll notice a new codes, providing different sources for different screen resolutions.

New WordPress Code for Images

Let’s examine the new image codes:

<img
src="http://www.yourdomain.co.il/wp-content/uploads/2016/01/featured_blog_holycow.jpg"
sizes="(max-width: 1000px) 800px, 100vw"
srcset="http://www.yourdomain.co.il/wp-content/uploads/2016/01/featured_blog_holycow-800x600.jpg 800w,
http://www.yourdomain.co.il/wp-content/uploads/2016/01/featured_blog_holycow-1000x800.jpg 1200w"
alt="Holy Cow!" />

The new elements are sizes and srcset.

While srcset is generation by WordPress automatically, providing a selection of available image sizes, sizes tag is related to your theme content width, and tells when to use this responsive images.

So determine largest required width of your images, and modify sizes to your needs.

I.e. if my theme has a sidebar 200px and my main content width is 1000px, so my site content width is 1200px, my images should be 1000px minimum width. Then I’ll want to use an image with a width 1000px or more.

But when my site width is resized in browser to 1000px width, content column will use 800px, so I could use 800px width image.

sizes="(max-width: 1000px) 800px, 100vw"
  1. Red text is a media query,
  2. orange text is image size to use with it and
  3. blue size is a default size to use, 100vw is the largest image size.

It’s easy to determine breakpoints with Resize > Display window size in title option of Web Developer plugin and you may check content size in Firebug.

Notice that such responsive images technique doesn’t work in older browsers, i.e. Internet Explorer (Edge is ok). In such case, default size will be used.

Make Changes to Your Theme

Now we need to change sizes to what we need in our theme. In your theme functions.php add:

// change sizes on resp imgs
function adjust_image_sizes_attr( $sizes, $size ) {
$sizes = '(max-width: 1000px) 800px, 100vw';
return $sizes;
}
add_filter( 'wp_calculate_image_sizes', 'adjust_image_sizes_attr', 10 , 2 );

This way when browser window size area is less then 1000px, 800px width image will display. if it is larger, largest available size would show.

Disable Responsive Images

If we need to disable responsive images completely, use this code:

// disable resp imgs
function disable_srcset( $sources ) {
return false;
}
add_filter( 'wp_calculate_image_srcset', 'disable_srcset' );

There is a big discussion going on here, if you need more info 🙂

Share:
This entry was posted in WordPress and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *