image_get_intermediate_size()
Retrieves the image's intermediate size (resized) path, width, and height.
The $size parameter can be an array with the width and height respectively. If the size matches the 'sizes' metadata array for width and height, then it will be used. If there is no direct match, then the nearest image size larger than the specified size will be used. If nothing is found, then the function will break out and return false.
The metadata 'sizes' is used for compatible sizes that can be used for the parameter $size value.
The url path will be given, when the $size parameter is a string.
If you are passing an array for the $size, you should consider using add_image_size() so that a cropped version is generated. It's much more efficient than having to find the closest-sized image and then having the browser scale down the image.
Hooks from the function
Return
Array|false
. Array of file relative path, width, and height on success. Additionally includes absolute path and URL if registered size is passed to $size parameter. False on failure.
Usage
image_get_intermediate_size( $post_id, $size );
- $post_id(int) (required)
- Attachment ID.
- $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: 'thumbnail'
Examples
#1 Usage Example
Let's get the data of the attachment image 4831, medium
size:
$intermediate = image_get_intermediate_size( 4831, 'medium' ); print_r( $intermediate ); /* He will: Array ( [file] => setting2-120x14.png [width] => 120 [height] => 14 [mime-type] => image/png [path] => 2014/07/setting2-120x14.png [url] => http://wp-kama.ru/wp-content/uploads/2014/07/setting2-120x14.png ) */
#2 Specify an array in the $size parameter
Let's get the image data of attachment 4831, the specified size (i.e., the size may not be registered):
$intermediate = image_get_intermediate_size( 4831, [90,90] ); /* will return: Array ( [file] => setting2-120x14.png [width] => 90 [height] => 10 ) */
This code will pick it up the most suitable size from existing ones, but not generate a new one.
#3 Display a picture of the right size, if there is one
In this example, we output a picture if there is one and "no picture" if there isn't. Unlike image_downsize() which returns the URL in any case:
function get_image_link_if_exists( $size ){ global $post; // get the id of the post thumbnail $thumbnail_id = get_post_thumbnail_id( $post->ID ); // output the picture if there is one $image = image_get_intermediate_size( $thumbnail_id, $size ); if( $image ){ echo '<img src="'. $image['url'] .'" alt="" width="'. $image['width'] .'" height="'. $image['height'] .'" />'; } else { echo 'No picture'; } } get_image_link_if_exists('my_size');
Changelog
Since 2.5.0 | Introduced. |