Is WordPress scaling down your tall images? Here’s a fix!
Starting in WordPress 5.3, WordPress began automatically scaling down uploaded images larger than 2560px by 2560px. Previously we had shown a way to disable this feature completely (https://www.foxtrotmedia.com/blog/website-development/wordpress-scales-down-images/), which works, however there is a benefit to not allowing users to upload unnecessarily large files.
So WordPress provides a filter to adjust the threshold size:
// increase the image size threshold to 4000px function mynamespace_big_image_size_threshold( $threshold ) { return 4000; // new threshold } add_filter('big_image_size_threshold', 'mynamespace_big_image_size_threshold', 999, 1);
Which is great! However, often we would like to provide a max width for our images while still allowing them to be as tall as they need. This filter only allows you to provide a single value which is used for both a max height and a max width. So if you have an image that is taller than it is wide, it is going to scale down to a size that has a width smaller than your threshold. This could potentially create a “stretching” issue if you’re assuming images are a specific width and then setting them to 100% width.
With that in mind, we’ve developed a nice way to provide both a max width and a max height for this threshold! Just drop the following into your functions.php file and adjust your thresholds as needed:
// Set Image Threshold for Both Width and Height function custom_image_threshold($threshold, $imagesize) { $width_threshold = 1920; $height_threshold = 8000; $image_width = $imagesize[0]; $image_height = $imagesize[1]; if ($height_threshold > $width_threshold) { if ($image_height > $image_width) { return min($image_height/$image_width * $width_threshold, $height_threshold); } return $width_threshold; } else { if ($image_width > $image_height) { return min($image_width/$image_height * $height_threshold, $width_threshold); } return $height_threshold; } } add_filter('big_image_size_threshold', 'custom_image_threshold', 10, 2);
Now you have much more flexibility in defining your max image sizes!
Let us know in the comments if you have any comments or questions!