如何取消WordPress产品页面主图片的懒加载?
解决WooCommerce产品主图取消懒加载的两种方法
根据你提供的wp_get_attachment_image函数逻辑,有两种可靠的方式取消产品主图的懒加载:
方法1:直接修改模板文件(适合熟悉模板编辑的用户)
- 先把WooCommerce的模板文件
woocommerce/single-product/product-image.php复制到你的子主题对应目录下(比如your-child-theme/woocommerce/single-product/product-image.php),避免主题更新时覆盖修改。 - 在复制后的文件里找到调用
wp_get_attachment_image的代码行,通常类似这样:echo wp_get_attachment_image( $attachment_id, $size, $icon, $attr ); - 修改
$attr参数,直接传入'loading' => false:
或者如果原来的调用没有// 如果原来有$attr数组,就合并进去;如果没有,直接定义 $attr = wp_parse_args( $attr, array( 'loading' => false ) ); echo wp_get_attachment_image( $attachment_id, $size, $icon, $attr );$attr,直接写:echo wp_get_attachment_image( $attachment_id, $size, $icon, array( 'loading' => false ) ); - 保存文件,刷新产品页面,主图的
loading="lazy"属性就会被移除。
方法2:使用WordPress钩子(无需修改模板,更安全)
这种方法不需要改动模板文件,通过添加代码到子主题的functions.php或者自定义插件里:
add_filter( 'wp_get_attachment_image_attributes', 'disable_product_main_image_lazy_load', 10, 3 ); function disable_product_main_image_lazy_load( $attr, $attachment, $size ) { // 只针对产品页面的主图 if ( is_product() ) { // 匹配产品主图的默认尺寸 $product_image_size = apply_filters( 'woocommerce_single_product_image_size', 'woocommerce_single' ); if ( $size === $product_image_size ) { $attr['loading'] = false; } } return $attr; }
这段代码的作用是:
- 通过
wp_get_attachment_image_attributes钩子过滤图片属性 - 判断当前是否在产品单页,且图片使用的是产品主图尺寸
- 将
loading属性设为false,触发函数内部的移除逻辑,最终取消懒加载
原理说明
从你给出的wp_get_attachment_image内部代码可以看到:
// If the default value of
lazyfor theloadingattribute is overridden
// to omit the attribute for this image, ensure it is not included.
if ( array_key_exists( 'loading', $attr ) && ! $attr['loading'] ) {
unset( $attr['loading'] );
}
当我们传入'loading' => false时,函数会检测到该键存在且值为false,随即移除loading属性,从而取消懒加载。
内容的提问来源于stack exchange,提问作者Ads
相关产品推荐
相关产品推荐

