0

I've added a custom image size to my functions.php: add_image_size('banner', 1920, 300, true);

I'm loading images in this custom size, using wp_get_attachment_image() to get a srcset.
However Wordpress will only generate a srcset if the image(s) it needs in this srcset are actually present on the disk.

When an image (lets say 2000x2000 for illlustration purposes) is uploaded, Wordpress will crop it down to 1920x300, great.
But none of the smaller sizes it will later need for the srcset are created, unless the image is specifically uploaded in 1920x300.

Forcing users to upload in the exact size required seems terrible and I would prefer not to do this.
Adding extra custom images sizes would just result in differently cropped or scaled images.

How do I get Wordpress to resize uploaded images to the sizes wp_get_attachment_image() needs for srcsets?

1 Answer 1

0

srcset is populated with all sizes of the image that are the same aspect ratio as the original image.

The reason smaller images are added to srcset if you upload the exact size is because that means that the default resized versions like medium and large will have the same aspect ratio. However, when using a custom cropped image size those smaller sizes will be created with the same aspect ratio as the original image, not the cropped custom size.

The solution to this is to register additional custom sizes with add_image_size() that are smaller than the custom size but have the same aspect ratio. WordPress will then be able to use these to populate srcset when didplaying your custom size.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.