wp_img_tag_add_srcset_and_sizes_attr()
云策文档标注
概述
wp_img_tag_add_srcset_and_sizes_attr() 函数用于向现有的 HTML img 标签添加 srcset 和 sizes 属性,以支持响应式图像。它通过过滤器控制是否添加属性,并依赖 wp_image_add_srcset_and_sizes() 实现具体功能。
关键要点
- 函数接受三个参数:$image(HTML img 标签字符串)、$context(上下文信息)和 $attachment_id(附件 ID),返回添加了属性的 img 标签字符串。
- 通过 wp_img_tag_add_srcset_and_sizes_attr 过滤器(默认返回 true)控制是否添加 srcset 和 sizes 属性,返回非 true 值将跳过添加。
- 内部调用 wp_get_attachment_metadata() 获取图像元数据,然后使用 wp_image_add_srcset_and_sizes() 处理属性添加。
- 该函数自 WordPress 5.5.0 版本引入,常用于 wp_filter_content_tags() 等场景中优化图像标记。
代码示例
function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) {
$add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id );
if ( true === $add ) {
$image_meta = wp_get_attachment_metadata( $attachment_id );
return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
}
return $image;
}
原文内容
Adds srcset and sizes attributes to an existing img HTML tag.
Parameters
$imagestringrequired-
The HTML
imgtag where the attribute should be added. $contextstringrequired-
Additional context to pass to the filters.
$attachment_idintrequired-
Image attachment ID.
Source
function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) {
/**
* Filters whether to add the `srcset` and `sizes` HTML attributes to the img tag. Default `true`.
*
* Returning anything else than `true` will not add the attributes.
*
* @since 5.5.0
*
* @param bool $value The filtered value, defaults to `true`.
* @param string $image The HTML `img` tag where the attribute should be added.
* @param string $context Additional context about how the function was called or where the img tag is.
* @param int $attachment_id The image attachment ID.
*/
$add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id );
if ( true === $add ) {
$image_meta = wp_get_attachment_metadata( $attachment_id );
return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
}
return $image;
}
Hooks
- apply_filters( ‘wp_img_tag_add_srcset_and_sizes_attr’, bool $value, string $image, string $context, int $attachment_id )
-
Filters whether to add the
srcsetandsizesHTML attributes to the img tag. Defaulttrue.
Changelog
| Version | Description |
|---|---|
| 5.5.0 | Introduced. |