wp_get_attachment_image_sizes()
云策文档标注
概述
wp_get_attachment_image_sizes() 函数用于获取图像附件的 'sizes' 属性值,适用于响应式图像处理。它基于附件ID、图像尺寸和元数据计算并返回一个字符串或false。
关键要点
- 函数返回图像附件的 'sizes' 属性值,用于HTML的sizes属性,支持响应式设计。
- 参数包括必需的附件ID、可选的图像尺寸(默认为'medium')和可选的图像元数据。
- 内部调用wp_get_attachment_image_src()获取图像源,并依赖wp_calculate_image_sizes()进行计算。
- 如果图像不存在或无法获取,函数返回false。
代码示例
function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
$image = wp_get_attachment_image_src( $attachment_id, $size );
if ( ! $image ) {
return false;
}
if ( ! is_array( $image_meta ) ) {
$image_meta = wp_get_attachment_metadata( $attachment_id );
}
$image_src = $image[0];
$size_array = array(
absint( $image[1] ),
absint( $image[2] ),
);
return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
}注意事项
- 确保提供的附件ID有效,否则函数可能返回false。
- 图像尺寸参数可以是注册的图像尺寸名称或像素宽度和高度的数组。
- 如果未提供image_meta,函数会自动从附件元数据中获取。
- 此函数自WordPress 4.4.0版本引入,相关函数包括wp_calculate_image_sizes()和wp_get_attachment_image_src()。
原文内容
Retrieves the value for an image attachment’s ‘sizes’ attribute.
Description
See also
Parameters
$attachment_idintrequired-
Image 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
'medium'. $image_metaarray|nulloptional-
The image meta data as returned by ‘wp_get_attachment_metadata() ‘.
Default:
null
Source
function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
$image = wp_get_attachment_image_src( $attachment_id, $size );
if ( ! $image ) {
return false;
}
if ( ! is_array( $image_meta ) ) {
$image_meta = wp_get_attachment_metadata( $attachment_id );
}
$image_src = $image[0];
$size_array = array(
absint( $image[1] ),
absint( $image[2] ),
);
return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
}
Changelog
| Version | Description |
|---|---|
| 4.4.0 | Introduced. |