You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce购物车页移除cart-item-thumbnail的srcset属性?

WooCommerce购物车图片srcset问题解决方案

问题背景

跨浏览器测试WooCommerce购物车页时,发现添加/删除商品、修改地址后,cart-item-thumbnail图片偶尔消失,排查确认是srcset属性导致。尝试用wp_calculate_image_srcset过滤器结合is_cart()条件仅在购物车页移除该属性,但is_cart()在钩子上下文失效,导致全站图片srcset被移除;适配针对the_post_thumbnail('full')的移除函数到my_small_size尺寸和woocommerce_cart_item_thumbnail过滤器,也未达预期。

可行解决方案

1. 精准控制:购物车页+指定尺寸移除srcset

通过wp_calculate_image_srcset过滤器,同时判断页面是否为购物车页、图片尺寸是否为my_small_size,解决is_cart()失效问题:

add_filter( 'wp_calculate_image_srcset', 'remove_srcset_for_cart_and_target_size', 10, 5 );
function remove_srcset_for_cart_and_target_size( $sources, $size_array, $image_src, $image_meta, $attachment_id ) {
    // 可靠判断购物车页(避免is_cart()失效)
    global $wp;
    $is_cart = isset( $wp->query_vars['cart'] ) || is_cart();
    
    // 获取my_small_size的尺寸参数
    $target_size = 'my_small_size';
    $custom_sizes = wp_get_additional_image_sizes();
    $target_dim = isset( $custom_sizes[$target_size] ) ? [ $custom_sizes[$target_size]['width'], $custom_sizes[$target_size]['height'] ] : [];
    
    // 满足任一条件则移除srcset
    if ( $is_cart || ( $size_array == $target_dim ) ) {
        return false;
    }
    
    return $sources;
}

2. 直接修改购物车缩略图输出

通过woocommerce_cart_item_thumbnail过滤器,直接剥离图片HTML中的srcset和sizes属性,仅影响购物车页缩略图:

add_filter( 'woocommerce_cart_item_thumbnail', 'strip_srcset_from_cart_thumbnails', 10, 3 );
function strip_srcset_from_cart_thumbnails( $thumbnail_html, $cart_item, $cart_item_key ) {
    // 移除srcset属性
    $thumbnail_html = preg_replace( '/\ssrcset="[^"]*"/', '', $thumbnail_html );
    // 移除关联的sizes属性
    $thumbnail_html = preg_replace( '/\ssizes="[^"]*"/', '', $thumbnail_html );
    return $thumbnail_html;
}

3. 全局移除指定尺寸图片的srcset

如果需要所有使用my_small_size的图片都去掉srcset,可使用以下代码:

add_filter( 'wp_calculate_image_srcset', 'remove_srcset_for_my_small_size', 10, 5 );
function remove_srcset_for_my_small_size( $sources, $size_array, $image_src, $image_meta, $attachment_id ) {
    $target_size = 'my_small_size';
    $custom_sizes = wp_get_additional_image_sizes();
    
    if ( isset( $custom_sizes[$target_size] ) ) {
        $target_w = $custom_sizes[$target_size]['width'];
        $target_h = $custom_sizes[$target_size]['height'];
        
        if ( $size_array[0] == $target_w && $size_array[1] == $target_h ) {
            return false;
        }
    }
    
    return $sources;
}

注意事项

  • 代码添加到主题的functions.php文件,或自定义插件中;
  • 修改后清空网站缓存和浏览器缓存,确保生效;
  • 若is_cart()仍失效,优先使用全局$wp对象判断购物车页,避免条件标签未初始化的问题。

内容的提问来源于stack exchange,提问作者timholz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 22:30:48