WooCommerce购物车商品标题无法显示2个以上变体问题求助
WooCommerce购物车变体标题显示问题解决
问题根源
- 多属性仅显示前2个:你使用的
woocommerce_product_variation_title_include_attributes钩子确实能开启属性显示,但WooCommerce内置的wc_get_formatted_variation函数默认会隐藏只有单个选项的属性,导致3个属性中若有一个是唯一值,就只会显示另外两个。 - 单个属性值不显示:当某个属性只有一个变体选项(如仅Short无Tall),WooCommerce默认认为这是产品默认状态,不会在标题中展示,仅当该属性存在多个选项时才显示。
解决方案
将以下代码添加到主题functions.php文件或自定义插件中:
// 强制变体标题包含所有属性 add_filter( 'woocommerce_product_variation_title_include_attributes', '__return_true' ); // 重写属性格式化逻辑,显示所有属性值(含唯一值) add_filter( 'woocommerce_formatted_variation_attributes', 'display_all_variation_attributes', 10, 3 ); function display_all_variation_attributes( $formatted_attrs, $product, $attrs ) { $new_formatted = array(); foreach ( $attrs as $key => $value ) { // 获取属性名称 $taxonomy = wc_attribute_taxonomy_name( $key ); $attr_name = taxonomy_exists( $taxonomy ) ? wc_get_attribute( $taxonomy )->get_name() : ucfirst( $key ); // 强制添加所有属性到标题 $new_formatted[ $attr_name ] = $value; } return $new_formatted; } // 可选:自定义变体标题的属性分隔符 add_filter( 'woocommerce_product_variation_title_attributes_separator', function() { return ' - '; });
效果说明
- 3个及以上属性的变体,标题会完整显示所有属性值(示例:商品名 - 变体1、变体2、变体3)
- 单个属性值的变体,该属性会直接显示在标题中(无需创建同属性的其他变体)
内容的提问来源于stack exchange,提问作者user20017364
相关产品推荐
相关产品推荐

