为WooCommerce可变产品添加不同零售价与促销价后缀
解决WooCommerce可变产品价格后缀显示问题
你的问题核心是可变产品的价格存储在变体中,而非主产品本身,直接调用get_sale_price()和get_regular_price()会返回0,因为主产品没有设置价格。以下是修正后的代码,同时兼容可变产品和简单产品的价格后缀需求:
add_filter( 'woocommerce_get_price_html', 'custom_price_suffixes', 100, 2 ); function custom_price_suffixes( $price, $product ) { // 处理可变产品 if ( $product->is_type('variable') ) { // 获取可变产品的最低/最高常规价和促销价(true参数返回纯数值) $min_regular = $product->get_variation_regular_price( 'min', true ); $max_regular = $product->get_variation_regular_price( 'max', true ); $min_sale = $product->get_variation_sale_price( 'min', true ); $max_sale = $product->get_variation_sale_price( 'max', true ); if ( $product->is_on_sale() ) { $sale_suffix = ' /SQFT with 315 sqft (pallet) minimum purchase'; $regular_suffix = ' /SQFT'; // 处理价格区间(最低/最高价不同时显示范围) $regular_price = ($min_regular !== $max_regular) ? wc_price( $min_regular ) . ' - ' . wc_price( $max_regular ) . $regular_suffix : wc_price( $min_regular ) . $regular_suffix; $sale_price = ($min_sale !== $max_sale) ? wc_price( $min_sale ) . ' - ' . wc_price( $max_sale ) . $sale_suffix : wc_price( $min_sale ) . $sale_suffix; $price = '<del>' . $regular_price . '</del> <ins>' . $sale_price . '</ins>'; } else { // 无促销时的价格显示 $price = ($min_regular !== $max_regular) ? wc_price( $min_regular ) . ' - ' . wc_price( $max_regular ) . ' /SQFT' : wc_price( $min_regular ) . ' /SQFT'; } } // 处理简单产品及其他类型产品 else { if ( $product->is_on_sale() ) { $sale_price = wc_price( $product->get_sale_price() ) . ' /SQFT with 315 sqft (pallet) minimum purchase'; $regular_price = wc_price( $product->get_regular_price() ) . ' /SQFT'; $price = '<del>' . $regular_price . '</del> <ins>' . $sale_price . '</ins>'; } else { $price = wc_price( $product->get_price() ) . ' /SQFT'; } } return $price; }
代码说明:
- 可变产品处理:使用
get_variation_regular_price()和get_variation_sale_price()方法获取变体的最低/最高价格,避免主产品价格为0的问题。 - 价格区间适配:如果可变产品的变体价格有差异,会显示价格范围(比如
$12.99 - $15.99 /SQFT),否则显示单一价格。 - 后缀区分:严格按照需求为零售价添加
/SQFT,促销价添加带起订量的后缀。 - 兼容性:同时支持简单产品和可变产品,不影响其他产品类型的价格展示。
内容的提问来源于stack exchange,提问作者Stephen Williamson
相关产品推荐
相关产品推荐

