Your browser is no longer supported. Please upgrade your browser to improve your experience.

Avoid using Timber’s resize filter for cropping images in production

Photo of Matthew Dixon

By Matthew Dixon
4th of September, 2021

A few years back I wrote an article about generating responsive images with Timber’s resize() filter whilst working for the excellent Go Tripod. I used this filter a lot when I first started using Timber as it can massively reduce the number of cropped images generated by WordPress. Crops defined with the native add_image_size() function are applied to every item uploaded to the media library meaning we usually end up with many superfluous images sat on the server that are never used on the front-end, whereas the resize() filter generates these assets when a page is first loaded and only for the image specified, not the entire media library.

This is a great way to save hard drive space but there are a few caveats…

Plugin compatibility


One reason to not use resize() is compatibility with plugins. Image manipulation and compression plugins will only work with assets WordPress knows about, ie. those generated by native functions like add_image_size(). I tend to include the super handy Crop-Thumbnails plugin on my builds as it gives editors the ability to change the default crop position (centred vertically and horizontally) on an image after uploading it to the media library – this means no worrying about manually cropping beforehand without seeing the image in situ, but it won’t work with resize().

Core compatibility


WordPress ships with a huge amount of functionality ready to be used out of the box. Much of this can be leveraged in the form of actions, filters and functions, and one of many popular functions is wp_get_attachment_image_srcset(). Pass an image ID and defined size as arguments and it’ll return a string in srcset format including all available images of the same aspect ratio on the server – thanks, WordPress!

Sadly this won’t work with resize() either as, again, an image size needs to have been defined by WordPress in order for WordPress to communicate with it.

Content Delivery Networks


Many developers have reported issues using the resize() filter with CDNs leading to broken images and time wasted. The general consensus now seems to be to stick with the native add_image_size() function for defining sizes in production – more images but less breakages.

The resize() filter doesn’t work with CDNs. WordPress doesn’t know about resized Timber image sizes. Consequently, any plugin that adds CDN support doesn’t either.

Is there a workaround? The current workaround is to use WordPress image sizes

Will it work in the future? Short answer: probably not with the current API.

Excerpts from Lukas Gächter’s comment on GitHub