Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Force WordPress to use cropped intermediates for cropped image_sizes to maintain aspect ratios.
<?php
/* Force wp_get_attachment_image_src to always pick a cropped intermediate size.
* If we define a sequence of srcset-friendly image_sizes like this:
* add_image_size('gallery', 1000, 750, true);
* add_image_size('gallery_1', 707, 530, true);
* add_image_size('gallery_2', 500, 375, true);
* then WordPress might pick the image's original, _uncropped_, size, which
* might have a wrong aspect ratio. To limit wp_get_attachment_image() to
* cropped intermediates with the right aspect ratio only, we have to manually
* check the availability of the files.
*/
add_filter('wp_get_attachment_image_src', function ($image, $attachment_id, $size, $icon ) {
global $_wp_additional_image_sizes; // let's hope this doesn't disappear
// if size is given as array ([width, height]), bail out early
if (is_array($size)) {
return $image;
}
// if requested size is not cropped, bail out early
if (!$_wp_additional_image_sizes[$size]['crop']) {
return $image;
}
// get 'suffixed' size names
$candidates = array_filter($_wp_additional_image_sizes, function ($key) use ($size) {
return substr($key, 0, strlen($size)) === $size;
}, ARRAY_FILTER_USE_KEY);
foreach ($candidates as $ck => $cv) {
$image_try = image_get_intermediate_size($attachment_id, $ck);
// return the first match - make sure that sizes are appropriately named / sorted
if ($image_try !== false) {
// return in weird array format
return [$image_try['url'], $image_try['width'], $image_try['height'], 1];
}
}
}, 4, 10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment