image_downsize()
Scale an image to fit a particular size (such as 'thumb' or 'medium').
The URL might be the original image, or it might be a resized version. This function won't create a new resized copy, it will just return an already resized one if it exists.
A plugin may use the image_downsize filter to hook into and offer image resizing services for images. The hook must return an array with the same elements that are normally returned from the function.
Hooks from the function
Return
Array|false
. Array of image data, or boolean false if no image is available.
Usage
image_downsize( $id, $size );
- $id(int) (required)
- Attachment ID for image.
- $size(string|int[])
- Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order).
Default: 'medium'
Examples
#1 Get image URL of medium size
Let's write a similar to wp_get_attachment_thumb_url() function that will get the medium
size of the attachment image, but not thumbnail
size.
$id is the ID of the attachment.
function wp_get_attachment_medium_url( $id ){ $medium_array = image_downsize( $id, 'medium' ); $medium_path = $medium_array[0]; return $medium_path; }
#2 How the function works
Suppose we have an attachment with ID 55 - it's a picture: http://example.com/wp-content/uploads/2014/02/wix.png
with a size of 500x258 pixels. In the settings of media files we have the following sizes for images: 80x80
, 300x300
, 1000x1000
. So, when loading this image, WP created two smaller copies: 80x80
, 300x300
.
Now see what the function will get when you specify different sizes:
$img = image_downsize( 55, 'full' ); /* Array ( [0] => http://example.com/wp-content/uploads/2014/02/wix.png [1] => 500 [2] => 258 [3] => ) */ $img = image_downsize( 55, 'thumbnail' ); /* Array ( [0] => http://example.com/wp-content/uploads/2014/02/wix-80x80.png [1] => 80 [2] => 80 [3] => 1 ) */ $img = image_downsize( 55 ); /* Array ( [0] => http://example.com/wp-content/uploads/2014/02/wix-300x258.png [1] => 300 [2] => 258 [3] => 1 ) */ $img = image_downsize( 55, array(100, 90) ); /* Array ( [0] => http://example.com/wp-content/uploads/2014/02/wix.png [1] => 100 [2] => 51 [3] => ) */ $img = image_downsize( 55, array(100, 80) ); /* Array ( [0] => http://example.com/wp-content/uploads/2014/02/wix-80x80.png [1] => 80 [2] => 80 [3] => 1 ) */
Changelog
Since 2.5.0 | Introduced. |