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.
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 »
Email @ 50: Email Development
Email development has always been the bane of a web developer's existence. You have to use outdated methods and don't have access to the full modern web to create a nice looking email that thousands of people will see. It's like asking a Nascar mechanic to create a car using only tools from the 90s - it can be done but its more than a pain.Read More »