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

WooCommerce根据变体名称切换商品侧边栏图片

解决WooCommerce变体切换对应显示不同图片的问题

步骤1:修改后端PHP函数

原代码固定输出单张图片,我们调整为根据商品默认变体的属性值输出对应图片,同时给图片元素加标识方便前端控制:

function image_by_variation() {
    global $product;
    
    // 仅对可变商品执行逻辑
    if ( ! $product->is_type('variable') ) return;
    
    // 获取默认变体的type-2属性值
    $default_attrs = $product->get_default_attributes();
    $type2_val = isset($default_attrs['type-2']) ? $default_attrs['type-2'] : '';
    
    // 定义变体值与图片的映射关系
    $image_map = [
        'repaired' => '你的image1完整URL',
        'never-repaired' => '你的image2完整URL'
    ];
    
    // 确定要显示的图片地址
    $target_img = isset($image_map[$type2_val]) ? $image_map[$type2_val] : '';
    
    if ($target_img) {
        echo '<div class="var_img"><img id="var-banner" src="' . esc_url($target_img) . '" height="200" width="500"></div>';
    }
}

步骤2:添加前端JS监听变体切换

WooCommerce变体选择是前端交互,需要监听切换事件来更新图片:

jQuery(document).ready(function($) {
    // 监听变体选中事件
    $('form.variations_form').on('show_variation', function(event, variation) {
        // 获取当前选中的type-2属性值
        var selected_type2 = variation.attributes['attribute_type-2'];
        // 图片映射(和PHP里保持一致)
        var img_map = {
            'repaired': '你的image1完整URL',
            'never-repaired': '你的image2完整URL'
        };
        
        // 更新图片地址
        if (img_map[selected_type2]) {
            $('#var-banner').attr('src', img_map[selected_type2]);
        }
    });
    
    // 监听变体重置事件(可选,恢复默认图片)
    $('form.variations_form').on('hide_variation', function() {
        $('#var-banner').attr('src', '你的image1完整URL');
    });
});

注意事项

  • 把代码中的你的image1完整URL和你的image2完整URL替换为实际图片地址(比如https://你的域名/wp-content/uploads/2024/05/repaired-banner.jpg)
  • 若商品是单变体(非可变商品),可简化PHP代码:直接用$product->get_attribute('type-2')获取属性值后判断输出图片

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:50:35