Responsive Cropped Images in WordPress
WordPress 4.4 added support for
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.
add_image_size('header-thumb', 1170, 400, true);
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
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.
What's the JAMstack?
As a front-end developer in 2020, it is time that I fulfill the FEDeral mandate that I publish words regarding the JAMStack. If you follow too many developers on Twitter, it’s likely you’ve heard about the Next Big Thing in web development, but I’d like to put this trend (fad? movement?) into context to better understand what’s truly new about this approach and whether it’s worth using.Read More »