WordPress Lies About Image Sizes / Dimensions

There are a few functions available to retrieve the URL and size of an image in the WordPress Media Library, but few people know that these functions will often lie about an image’s dimensions.

As an example, let’s define a custom image size of 1000 x 1000 cropped, and use image_downsize() to retrieve the URL and size of an image ID (this example can be used with wp_get_attachment_image_src() as well). I’ll use list() in the example, instead of an array variable for the return values, to keep the code more readable. ;-)

WordPress will return a URL for the image and the values of $width / $height may be 1000 / 1000 – it all depends on several factors.

If the image was uploaded when ‘my-custom-size’ existed, then WordPress will return 1000 / 1000 and the correct URL. If ‘my-custom-size’ did not exist when an image was uploaded, then WordPress will return a larger image (if possible) and if it is cropped, the $width / $height values will be 1000 / 1000, even if the image is actually larger. If the larger image is not cropped, then the $width or $height could be 1000, while the other will be a smaller value. And if the original image is smaller than 1000 x 1000, then WordPress returns the largest size it can, which may or may not be cropped.

But the fun doesn’t stop here… ;-) If you’re calling image_downsize() while you’re on a Post / Page editing page, WordPress will lie about the image’s dimensions if they exceed the width of the editing window, giving you scaled down dimensions instead – it doesn’t matter if you’re planning on using the image within the editor or not.

So, how can we manage this mine-field and get accurate image URLs and dimensions?

The first, and easiest part, is to tell WordPress not to scale down our custom image size on editing pages. We can do this using the ‘editor_max_image_size’ filter.

The second part will require a bit more code to verify that our custom size exists for that image, and create / re-create it if it doesn’t.