WooCommerce 可变产品属性值判断及价格展示逻辑调整实现
原有判断逻辑失效的原因
- 第一版代码问题:
- WooCommerce新版的
WC_Product对象没有直接对外暴露->id属性,直接调用会拿到空值,根本无法匹配对应产品的属性数据 get_the_terms()返回的是包含分类法对象的数组,每个元素包含term_id、name、slug等结构化属性,不是纯字符串数组,直接用in_array()匹配字符串值永远无法命中
- WooCommerce新版的
- 第二版代码问题:
has_term()默认匹配分类项的slug值,如果传入的是首字母大写的'Rent',但实际对应属性项的slug是全小写的'rent',会直接匹配失败- 价格过滤钩子的执行时机早于WooCommerce全局
$post对象的初始化,has_term()强依赖全局$post上下文,这种场景下哪怕产品真的绑定了对应属性,也会返回判断为假
可直接嵌入functions.php的修正代码
function wc_varb_price_range( $wcv_price, $product ) { // 安全获取产品ID,做属性匹配判断 $product_id = $product->get_id(); $pricing_terms = get_the_terms( $product_id, 'pa_pricing' ); $has_rent_attr = false; // 增加错误拦截,防止函数返回空值/错误值引发页面报错 if ( ! is_wp_error( $pricing_terms ) && ! empty( $pricing_terms ) ) { foreach ( $pricing_terms as $term_item ) { // 匹配属性项的slug,可根据站点实际设置的slug值调整此处判断条件 if ( $term_item->slug === 'rent' ) { $has_rent_attr = true; break; } } } // 原有可变产品价格计算逻辑 $wcv_reg_min_price = $product->get_variation_regular_price( 'min', true ); $wcv_reg_max_price = $product->get_variation_regular_price( 'max', true ); $wcv_min_sale_price = $product->get_variation_sale_price( 'min', true ); $wcv_max_sale_price = $product->get_variation_sale_price( 'max', true ); $wcv_max_price = $product->get_variation_price( 'max', true ); $wcv_min_price = $product->get_variation_price( 'min', true ); $wcv_price = ( $wcv_min_sale_price == $wcv_reg_min_price ) ? wc_price( $wcv_reg_min_price ) : '<del>' . wc_price( $wcv_reg_min_price ) . '</del>' . '<ins>' . wc_price( $wcv_min_sale_price ) . '</ins>'; $wcv_bo_price = ( $wcv_max_sale_price == $wcv_reg_max_price ) ? wc_price( $wcv_reg_max_price ) : '<del>' . wc_price( $wcv_reg_max_price ) . '</del>' . '<ins>' . wc_price( $wcv_max_sale_price ) . '</ins>'; // 未匹配到Rent属性时,替换原有带租赁文案的价格展示 if ( ! $has_rent_attr ) { return ( $wcv_min_price == $wcv_max_price ) ? $wcv_price : sprintf( '%1$s - %2$s', $wcv_price, $wcv_bo_price ); } // 匹配到Rent属性时,保留原有租赁类价格展示逻辑 $prefix = sprintf( '%s: ', __( 'Rent from', 'wcvp_range' ) ); return ( $wcv_min_price == $wcv_max_price ) ? $wcv_price : sprintf('%s%s', $prefix, $wcv_price) . " per month <br> Buy for <span class='woocommerce-Price-amount amount'>" . $wcv_bo_price . "</span>"; } add_filter( 'woocommerce_variable_sale_price_html', 'wc_varb_price_range', 10, 2 ); add_filter( 'woocommerce_variable_price_html', 'wc_varb_price_range', 10, 2 );
自定义调整提示
- 代码中属性匹配环节目前固定匹配slug为
rent的属性项,可在「产品-属性」设置页找到对应属性项的实际slug值,修改判断条件适配 - 未匹配到Rent属性时的返回文本目前设置为简洁价格范围格式,可根据需求替换为指定的定制展示文本
内容的提问来源于stack exchange,提问作者Mark__Thomas
相关产品推荐
相关产品推荐

