image_get_intermediate_size()WP 2.5.0

Gets an array of image-attachment data of the specified size: thumbnail, medium etc., if it exists.

If you use an array for $size, it is recommended to register the required size using add_image_size() - this is sometimes more efficient than finding the nearest larger size and then scaling it down to the required size in the browser.

As a result, the image URL will be returned only if the $size parameter is specified as a string.

1 time — 0.001427 sec (very slow) | 50000 times — 1.51 sec (fast) | PHP 7.1.5, WP 4.8.1
Hooks from the function

Returns

Array|false. false if the size does not exist and an array of image data if the size exists:

If a string is passed in $size and an exact matching size is found:
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
)

When an exact size is not found, but a nearest larger image is found:
Array (
	[file] => setting2-120x14.png
	[width] => 90
	[height] => 10
)

Usage

$image = image_get_intermediate_size( $post_id, $size );
$post_id(int) (required)
ID of the image attachment
$size(string/array)

Image size.

Here you specify a registered image size in WordPress; out of the box the following sizes are available:

thumb
thumbnail
medium
large
post-thumbnail

Custom images are registered using add_image_size().

You can pass an array to the parameter, for example [200, 300] - width and height in pixels. If such a size matches one of the already generated image sizes, the corresponding thumbnail will be used. If there is no exact match, the nearest suitable larger size will be returned. If there is no suitable larger size, the function will return false.

Default: 'thumbnail'

Examples

0

#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
)
*/
0

#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.

0

#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.

image_get_intermediate_size() code WP 6.9.1

function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
	$imagedata = wp_get_attachment_metadata( $post_id );

	if ( ! $size || ! is_array( $imagedata ) || empty( $imagedata['sizes'] ) ) {
		return false;
	}

	$data = array();

	// Find the best match when '$size' is an array.
	if ( is_array( $size ) ) {
		$candidates = array();

		if ( ! isset( $imagedata['file'] ) && isset( $imagedata['sizes']['full'] ) ) {
			$imagedata['height'] = $imagedata['sizes']['full']['height'];
			$imagedata['width']  = $imagedata['sizes']['full']['width'];
		}

		foreach ( $imagedata['sizes'] as $_size => $data ) {
			// If there's an exact match to an existing image size, short circuit.
			if ( (int) $data['width'] === (int) $size[0] && (int) $data['height'] === (int) $size[1] ) {
				$candidates[ $data['width'] * $data['height'] ] = $data;
				break;
			}

			// If it's not an exact match, consider larger sizes with the same aspect ratio.
			if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
				// If '0' is passed to either size, we test ratios against the original file.
				if ( 0 === $size[0] || 0 === $size[1] ) {
					$same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $imagedata['width'], $imagedata['height'] );
				} else {
					$same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $size[0], $size[1] );
				}

				if ( $same_ratio ) {
					$candidates[ $data['width'] * $data['height'] ] = $data;
				}
			}
		}

		if ( ! empty( $candidates ) ) {
			// Sort the array by size if we have more than one candidate.
			if ( 1 < count( $candidates ) ) {
				ksort( $candidates );
			}

			$data = array_shift( $candidates );
		} elseif ( ! empty( $imagedata['sizes']['thumbnail'] )
			&& $size[0] <= $imagedata['sizes']['thumbnail']['width']
			&& $size[1] <= $imagedata['sizes']['thumbnail']['width']
		) {
			/*
			 * When the size requested is smaller than the thumbnail dimensions, we
			 * fall back to the thumbnail size to maintain backward compatibility with
			 * pre-4.6 versions of WordPress.
			 */
			$data = $imagedata['sizes']['thumbnail'];
		} else {
			return false;
		}

		// Constrain the width and height attributes to the requested values.
		list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );

	} elseif ( ! empty( $imagedata['sizes'][ $size ] ) ) {
		$data = $imagedata['sizes'][ $size ];
	}

	// If we still don't have a match at this point, return false.
	if ( empty( $data ) ) {
		return false;
	}

	// Include the full filesystem path of the intermediate file.
	if ( empty( $data['path'] ) && ! empty( $data['file'] ) && ! empty( $imagedata['file'] ) ) {
		$file_url     = wp_get_attachment_url( $post_id );
		$data['path'] = path_join( dirname( $imagedata['file'] ), $data['file'] );
		$data['url']  = path_join( dirname( $file_url ), $data['file'] );
	}

	/**
	 * Filters the output of image_get_intermediate_size()
	 *
	 * @since 4.4.0
	 *
	 * @see image_get_intermediate_size()
	 *
	 * @param array        $data    Array of file relative path, width, and height on success. May also include
	 *                              file absolute path and URL.
	 * @param int          $post_id The ID of the image attachment.
	 * @param string|int[] $size    Requested image size. Can be any registered image size name, or
	 *                              an array of width and height values in pixels (in that order).
	 */
	return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
}