函数文档

image_downsize()

💡 云策文档标注

概述

image_downsize() 函数用于缩放图像以适应指定尺寸(如 'thumb' 或 'medium'),返回已存在的调整大小版本,而不会创建新副本。它支持通过 'image_downsize' 过滤器进行插件扩展。

关键要点

  • 函数接受附件 ID 和尺寸参数,尺寸可以是注册的图像尺寸名称或像素宽高数组。
  • 返回数组包含图像 URL、宽度、高度和是否为调整大小图像的布尔值,若无图像则返回 false。
  • 使用 'image_downsize' 过滤器可钩入并提供图像缩放服务,返回数组需与函数正常返回格式一致。
  • 函数内部处理非图像附件、中间尺寸获取和编辑器尺寸约束等逻辑。

代码示例

function wp_get_attachment_medium_url( $id )
{
    $medium_array = image_downsize( $id, 'medium' );
    $medium_path = $medium_array[0];

    return $medium_path;
}

注意事项

  • 函数不会生成新的调整大小图像,仅返回已存在的版本。
  • 对于非图像附件,会尝试从元数据中获取渲染图像。
  • 使用过滤器时需确保返回数组格式正确,以避免中断正常流程。

📄 原文内容

Scales an image to fit a particular size (such as ‘thumb’ or ‘medium’).

Description

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.

Parameters

$idintrequired
Attachment ID for image.
$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 'medium'.

Return

array|false Array of image data, or boolean false if no image is available.

  • 0 string
    Image source URL.
  • 1 int
    Image width in pixels.
  • 2 int
    Image height in pixels.
  • 3 bool
    Whether the image is a resized image.

Source

function image_downsize( $id, $size = 'medium' ) {
	$is_image = wp_attachment_is_image( $id );

	/**
	 * Filters whether to preempt the output of image_downsize().
	 *
	 * Returning a truthy value from the filter will effectively short-circuit
	 * down-sizing the image, returning that value instead.
	 *
	 * @since 2.5.0
	 *
	 * @param bool|array   $downsize Whether to short-circuit the image downsize.
	 * @param int          $id       Attachment ID for image.
	 * @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).
	 */
	$out = apply_filters( 'image_downsize', false, $id, $size );

	if ( $out ) {
		return $out;
	}

	$img_url          = wp_get_attachment_url( $id );
	$meta             = wp_get_attachment_metadata( $id );
	$width            = 0;
	$height           = 0;
	$is_intermediate  = false;
	$img_url_basename = wp_basename( $img_url );

	/*
	 * If the file isn't an image, attempt to replace its URL with a rendered image from its meta.
	 * Otherwise, a non-image type could be returned.
	 */
	if ( ! $is_image ) {
		if ( ! empty( $meta['sizes']['full'] ) ) {
			$img_url          = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url );
			$img_url_basename = $meta['sizes']['full']['file'];
			$width            = $meta['sizes']['full']['width'];
			$height           = $meta['sizes']['full']['height'];
		} else {
			return false;
		}
	}

	// Try for a new style intermediate size.
	$intermediate = image_get_intermediate_size( $id, $size );

	if ( $intermediate ) {
		$img_url         = str_replace( $img_url_basename, $intermediate['file'], $img_url );
		$width           = $intermediate['width'];
		$height          = $intermediate['height'];
		$is_intermediate = true;
	} elseif ( 'thumbnail' === $size && ! empty( $meta['thumb'] ) && is_string( $meta['thumb'] ) ) {
		// Fall back to the old thumbnail.
		$imagefile = get_attached_file( $id );
		$thumbfile = str_replace( wp_basename( $imagefile ), wp_basename( $meta['thumb'] ), $imagefile );

		if ( file_exists( $thumbfile ) ) {
			$info = wp_getimagesize( $thumbfile );

			if ( $info ) {
				$img_url         = str_replace( $img_url_basename, wp_basename( $thumbfile ), $img_url );
				$width           = $info[0];
				$height          = $info[1];
				$is_intermediate = true;
			}
		}
	}

	if ( ! $width && ! $height && isset( $meta['width'], $meta['height'] ) ) {
		// Any other type: use the real image.
		$width  = $meta['width'];
		$height = $meta['height'];
	}

	if ( $img_url ) {
		// We have the actual image size, but might need to further constrain it if content_width is narrower.
		list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );

		return array( $img_url, $width, $height, $is_intermediate );
	}

	return false;
}

Hooks

apply_filters( ‘image_downsize’, bool|array $downsize, int $id, string|int[] $size )

Filters whether to preempt the output of image_downsize() .

Changelog

Version Description
2.5.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Add a function to select medium attachment images

    Maybe you already know wp_get_attachment_thumb_url() ;. Now I’m showing how to do the same thing to return the url for the medium sized attachment.

    function wp_get_attachment_medium_url( $id )
    {
        $medium_array = image_downsize( $id, 'medium' );
        $medium_path = $medium_array[0];
    
        return $medium_path;
    }

    $id is the ID of the attachment. This can be really useful for plugins like WP-Choose-Thumb. With this function you can get the medium sized previews.