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

请求编写WooCommerce购物车商品标题下显示选中变体的代码

在WooCommerce购物车页面显示商品变体信息的代码实现

把下面这段代码放到你的主题(推荐用子主题)cart.php文件中商品标题的下方位置:

<?php
// 获取当前购物车项的产品对象
$product = apply_filters('woocommerce_cart_item_product', $_product, $cart_item, $cart_item_key);

// 判断是否为变体产品
if ($product->is_type('variation')) {
    // 获取变体的所有属性
    $attributes = $product->get_variation_attributes();
    
    if (!empty($attributes)) {
        echo '<div class="cart-item-variations" style="font-size: 0.9em; color: #666; margin-top: 4px;">';
        $variation_strings = array();
        foreach ($attributes as $attr_name => $attr_value) {
            // 将属性机器名转为友好显示名称
            $attr_label = wc_attribute_label(str_replace('pa_', '', $attr_name));
            $variation_strings[] = sprintf('%s: %s', $attr_label, $attr_value);
        }
        echo implode('、', $variation_strings);
        echo '</div>';
    }
}
?>

代码说明

  • 先获取当前购物车项对应的产品对象,判断是否为变体产品
  • 若为变体,提取所有已选择的属性信息,把属性的机器标识转为用户易懂的名称
  • 将属性名和属性值格式化为属性名: 属性值的形式,用顿号分隔展示
  • 自带简单的行内样式调整显示效果,你可以根据主题风格修改cart-item-variations类的CSS

注意事项

  • 别直接修改父主题的cart.php,用子主题修改能避免主题更新时代码被覆盖
  • 如果你的主题已经自定义了购物车模板,找到对应商品标题的位置插入代码即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:23:16