Responsive Cropped Images in WordPress
By:
Josie Flynn
on 12/19/2016
WordPress 4.4 added support for srcset
and sizes
, allowing the browser to pick the best version of an <img>
from a list of different sizes, which we covered in depth earlier this year. WordPress generates all of these different sizes when an author uploads an image, in addition to any custom sizes added by plugins or the current theme.
While implementing a full width featured image in a recent project, I ran into a confusing bug where srcset
wasn’t being generated for the custom image size added by our theme, resulting in a blurry image on high res devices and a much too large image on mobile. This size (named header-thumb
) is 1170×400 pixels and is configured to crop the original image if it’s not the same aspect ratio.
After spending quite some time reviewing the documentation, I stumbled across a thread on the WordPress developer blog that explained everything. Unfortunately, this wasn’t documented anywhere I could find on WordPress.org.
WordPress will only include images that match the same aspect ratio as the image in the âsrc’ attribute.
â WordPress core developer Joe McGill
Since there are no other thumbnails matching that aspect ratio, we need to add additional cropped sizes to compensate.
functions.php
Before
add_image_size('header-thumb', 1170, 400, true);
After
add_image_size('header-thumb-small', 585, 200, true); add_image_size('header-thumb-medium', 804, 275, true); add_image_size('header-thumb-large', 1170, 400, true); add_image_size('header-thumb', 2340, 800, true);
Now, wherever our theme calls the_post_thumbnail('header-thumb')
, we get an <img>
tag with the above sizes in its srcset
.
Note that the header-thumb
size was doubled to account for larger high DPI displays. Also, you’ll need to regenerate your media library’s thumbnails with the Regenerate Thumbnails plugin or wp-cli if you have existing images.
Related Posts
Component-Based Web Design
By:Morgan Plappert on 8/9/2024
Designers and developers are always looking for ways to make handoff easier, collaboration more seamless and our processes better aligned. Automation, consistency and efficiency, without compromising creativity. It’s a constant battle and often times, a balancing act.
Read More »Dive into the Sanity Structure Builder
By: Mark Biek on 6/13/2021
Sanity is the super fast, super customizable CMS that we're using as the backend for the new via.studio website. One of the more powerful concepts that Sanity is the Structure Builder which gives you the ability to customize how content is presented in the Sanity admin.
Read More »