函数文档

image_get_intermediate_size()

💡 云策文档标注

概述

image_get_intermediate_size() 函数用于获取图像附件的中等尺寸(即调整大小后的版本)的路径、宽度和高度信息。它支持通过字符串指定已注册的尺寸名称,或通过数组指定自定义宽度和高度值,并智能匹配最合适的图像尺寸。

关键要点

  • 函数接受两个参数:$post_id(附件ID,必填)和 $size(图像尺寸,可选,默认为 'thumbnail')。$size 可以是字符串(如 'medium')或数组(如 [800, 600])。
  • 当 $size 为数组时,函数会优先查找精确匹配的尺寸;若无匹配,则选择大于指定尺寸且宽高比相同的最近尺寸;若仍无结果,返回 false。
  • 返回值为数组或 false。成功时返回包含文件路径、宽度、高度等信息的数组;若传递已注册尺寸名称,还会包含绝对路径和URL。
  • 建议在使用数组 $size 时,通过 add_image_size() 注册裁剪版本以提高效率,避免浏览器缩放图像。
  • 函数内部依赖 wp_get_attachment_metadata() 获取元数据,并应用 'image_get_intermediate_size' 过滤器进行输出定制。

代码示例

// 示例:获取附件ID为 123 的 'medium' 尺寸图像信息
$image_info = image_get_intermediate_size( 123, 'medium' );
if ( $image_info ) {
    echo 'URL: ' . $image_info['url'];
    echo 'Width: ' . $image_info['width'];
    echo 'Height: ' . $image_info['height'];
}

// 示例:使用自定义尺寸数组 [800, 600]
$custom_size = image_get_intermediate_size( 123, [800, 600] );
if ( $custom_size ) {
    // 处理返回的数组
}

注意事项

  • 确保 $post_id 对应有效的图像附件,否则函数可能返回 false。
  • 当 $size 为数组且未找到匹配尺寸时,函数返回 false,需在代码中处理此情况。
  • 函数自 WordPress 2.5.0 版本引入,兼容性良好。

📄 原文内容

Retrieves the image’s intermediate size (resized) path, width, and height.

Description

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.

Parameters

$post_idintrequired
Attachment ID.
$sizestring|int[]optional
Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default 'thumbnail'.

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.

  • file string
    Filename of image.
  • width int
    Width of image in pixels.
  • height int
    Height of image in pixels.
  • path string
    Path of image relative to uploads directory.
  • url string
    URL of image.

Source

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 );
}

Hooks

apply_filters( ‘image_get_intermediate_size’, array $data, int $post_id, string|int[] $size )

Filters the output of image_get_intermediate_size()

Changelog

Version Description
2.5.0 Introduced.