WooCommerce:直接编辑可变产品添加属性时,修正代码获取正确颜色数
问题解决思路及修改代码
问题原因
你之前的代码判断条件用的是attribute_pa_color,这个是全局属性(通过后台「Products -- Attributes」添加的属性)的专属标识,这类属性会自动带上pa_前缀。而直接在可变产品编辑页添加的是自定义产品属性,它的键名格式是attribute_+属性名称小写(比如你添加的Color属性,键名实际是attribute_color),所以原代码找不到对应属性,导致$color_count返回0。
修改方案
方案1:直接从产品属性获取颜色选项数量(推荐)
这个方法不需要遍历所有变体,直接读取产品本身的Color属性配置,效率更高,能准确得到属性的所有取值数量:
add_action( 'woocommerce_before_add_to_cart_button', 'wc_display_product_variations_count' ); function wc_display_product_variations_count() { global $product; if( $product->is_type( 'variable' ) ) { $variations = $product->get_available_variations(); $variation_count = count( $variations ); $color_count = 0; // 获取产品的所有属性集合 $product_attributes = $product->get_attributes(); foreach ( $product_attributes as $attr_key => $attribute ) { // 匹配属性名称为Color(注意大小写和你设置的一致) if ( $attribute->get_name() === 'Color' ) { // 获取该属性的所有选项数量 $color_count = count( $attribute->get_options() ); break; } } echo '<small>(' . $color_count . ' Colors, ' . $variation_count . ' Variations)</small><br>'; } }
方案2:从变体中收集不重复的颜色值
这个方法会遍历所有可用变体,收集颜色值并去重,适合只统计有对应变体的颜色数量(如果某个颜色没有创建变体,不会被计数):
add_action( 'woocommerce_before_add_to_cart_button', 'wc_display_product_variations_count' ); function wc_display_product_variations_count() { global $product; if( $product->is_type( 'variable' ) ) { $variations = $product->get_available_variations(); $variation_count = count( $variations ); $color_values = array(); foreach( $variations as $variation ) { $variation_attributes = $variation['attributes']; // 遍历变体属性,找到颜色相关的键 foreach ( $variation_attributes as $attr_key => $attr_value ) { // 匹配自定义Color属性的键(attribute_color) if ( $attr_key === 'attribute_color' ) { $color_values[] = $attr_value; } } } // 去重后得到颜色数量 $color_count = count( array_unique( $color_values ) ); echo '<small>(' . $color_count . ' Colors, ' . $variation_count . ' Variations)</small><br>'; } }
内容的提问来源于stack exchange,提问作者user14847965
相关产品推荐
相关产品推荐

