wp_img_tag_add_loading_attr
云策文档标注
概述
wp_img_tag_add_loading_attr 是一个 WordPress 过滤器,用于控制图像标签的 loading 属性值,默认设置为 lazy 以实现懒加载。开发者可以通过此过滤器自定义属性值或禁用懒加载。
关键要点
- 过滤器 wp_img_tag_add_loading_attr 允许修改图像的 loading 属性值,默认值为 lazy。
- 返回 false 或空字符串将不添加 loading 属性,返回 true 将使用默认值 lazy。
- 参数包括 $value(属性值,可为字符串或布尔值)、$image(HTML img 标签)和 $context(调用上下文)。
- 此过滤器在 WordPress 5.5.0 中引入,常用于优化页面加载性能,特别是针对首屏图像。
代码示例
add_filter( 'wp_img_tag_add_loading_attr', function( $value, $image ){
if ( false !== strpos( $image, 'skip-lazy' ) ){
return false;
}
return true;
}, 10, 2 );注意事项
- 此过滤器可用于禁用特定图像的懒加载,例如通过检测自定义类如 skip-lazy 来优化首屏内容加载时间(LCP)。
- 相关函数包括 wp_img_tag_add_loading_optimization_attrs() 和 wp_img_tag_add_loading_attr()(已弃用)。
原文内容
Filters the loading attribute value to add to an image. Default lazy.
Description
Returning false or an empty string will not add the attribute.
Returning true will add the default value.
Parameters
$valuestring|bool-
The
loadingattribute value. Returning a falsey value will result in the attribute being omitted for the image. $imagestring-
The HTML
imgtag to be filtered. $contextstring-
Additional context about how the function was called or where the img tag is.
Source
$filtered_loading_attr = apply_filters(
'wp_img_tag_add_loading_attr',
isset( $optimization_attrs['loading'] ) ? $optimization_attrs['loading'] : false,
$image,
$context
);
Changelog
| Version | Description |
|---|---|
| 5.5.0 | Introduced. |
Skip to note 2 content
Kresimir Pendic
tl;dr ⨪ this will fix your LCP in pagespeed report for lazy loaded images above the fold
This filter is very useful for images above the fold that don’t need to be lazy loaded (for example logos, featured images etc) so we can hook this filter to read our images and parse for example some custom class that can set lazy loading attribute ON or OFF per image.
– by setting custom class `skip-lazy` inside admin under `Advanced > Additional Classes` inside image settings:
add_filter( 'wp_img_tag_add_loading_attr', function( $value, $image ){ if ( false !== strpos( $image, 'skip-lazy' ) ){ return false; } return true; }, 10, 2 );disables it