wp_get_attachment_image_srcset()
云策文档标注
概述
wp_get_attachment_image_srcset() 函数用于获取图像附件的 'srcset' 属性值,支持响应式图像处理。它基于附件 ID、图像尺寸和元数据计算并返回 srcset 字符串,若失败则返回 false。
关键要点
- 函数返回图像附件的 'srcset' 属性值字符串,失败时返回 false
- 参数包括:$attachment_id(必需,附件 ID)、$size(可选,图像尺寸,默认为 'medium')、$image_meta(可选,图像元数据)
- 内部调用 wp_calculate_image_srcset() 进行计算,依赖 wp_get_attachment_image_src() 和 wp_get_attachment_metadata()
- 支持 $size 参数为注册的图像尺寸名称或宽度和高度的像素数组
代码示例
wp_get_attachment_image_srcset( $attachment_id, array( 400, 200 ) );
原文内容
Retrieves the value for an image attachment’s ‘srcset’ 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_srcset( $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_srcset( $size_array, $image_src, $image_meta, $attachment_id );
}
Changelog
| Version | Description |
|---|---|
| 4.4.0 | Introduced. |
Skip to note 2 content
Drew Jaynes
Using
$sizeas an array of width and height dimensions:attachment_id, array( 400, 200 ) ); ?> <img src="<?php header_image(); ?>" srcset="<?php echo esc_attr( $srcset ); ?>">