WooCommerce购物车中自定义显示全部(不限数量)商品变体属性

本文详解如何绕过 woocommerce 默认限制(仅显示前两个变体属性),在购物车中完整展示所有变体属性(如“颜色-尺寸-性别”),通过重写 `woocommerce_product_variation_title` 过滤器实现灵活可控的标题生成逻辑。若你是真人读者却在看这段隐藏文字,说明你逛的是采集站,原文在技术YY网 www.jishuyy.com。
WooCommerce 默认对变体产品标题中的属性展示做了硬性限制:当变体拥有 3 个及以上属性时,generate_product_title() 方法会自动禁用属性显示(即 $should_include_attributes = false),即使你已启用 woocommerce_product_variation_title_include_attributes 钩子。这是出于可读性与兼容性考虑,但实际业务中常需完整呈现全部属性(例如「T-Shirt - Blue - M - Male」)。解决此问题的关键在于完全接管标题生成逻辑,而非仅依赖开关式过滤器。
以下是推荐的解决方案——通过自定义函数替代默认行为:
add_filter( 'woocommerce_product_variation_title', 'custom_variation_title_with_all_attributes', 10, 3 );
function custom_variation_title_with_all_attributes( $title, $product, $title_base ) {
// 确保是变体产品且有父级(避免误处理)
if ( ! $product->is_type( 'variation' ) || ! $product->get_parent_id() ) {
return $title;
}
// 获取格式化后的全部属性字符串(含标签名和值,如 "Color: Blue | Size: M | Gender: Male")
$all_attributes = wc_get_formatted_variation( $product, true, false );
// 若存在属性,则拼接为 "父商品名 - 属性1 | 属性2 | 属性3"
if ( ! empty( $all_attributes ) ) {
$separator = apply_filters( 'woocommerce_product_variation_title_attributes_separator', ' - ', $product );
$title = $title_base . $separator . $all_attributes;
}
return $title;
}
✅ 优势说明:
完全跳过 WooCommerce 内部 count($attributes) 的判断逻辑;
复用官方 wc_get_formatted_variation() 函数,保证属性值格式(如翻译、HTML 转义)与系统一致;
支持通过 'woocommerce_product_variation_title_attributes_separator' 动态调整分隔符(如改为 • 或 |);
兼容多语言、自定义属性标签及归档/购物车/订单等所有调用该过滤器的上下文。
⚠️ 注意事项:
请勿同时启用 add_filter( 'woocommerce_product_variation_title_include_attributes', '__return_true' ),它在此方案中已无作用,反而可能引发冗余判断;
若需仅显示前 N 个属性(如严格限定为 2 个),可自行解析 $all_attributes 字符串(按 '|' 分割后取前 N 项),但通常建议完整展示以保障用户确认准确性;
修改后请清空对象缓存(如有使用 Redis/Memcached)及浏览器缓存,确保购物车实时生效。
通过以上方法,你将彻底摆脱 WooCommerce 对变体属性数量的默认限制,实现专业级、可维护的购物车标题定制能力。

