You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce可变产品中替换显示的零价格为指定文本?

WooCommerce零价格替换为自定义文本(含可变产品修复)

原代码仅覆盖了可变产品的部分场景,导致零价格显示异常。以下是修正后的代码,可实现:

  • 简单产品零价格显示「Contact us for a unique quote!」
  • 可变产品价格范围含零价格时,将最低价格替换为「FREE」
  • 选中单个零价格变体时,显示「FREE」
add_filter( 'woocommerce_get_price_html', 'wtwh_price_free_zero', 9999, 2 );  
function wtwh_price_free_zero( $price, $product ) {
    // 处理可变产品
    if ( $product->is_type( 'variable' ) ) {
        $prices = $product->get_variation_prices( true );
        $min_price = current( $prices['price'] );
        $max_price = end( $prices['price'] );
        
        // 检查是否存在零价格变体
        if ( in_array( 0, $prices['price'], true ) ) {
            if ( $min_price !== $max_price ) {
                // 价格范围:替换零价格为FREE
                $price = wc_format_price_range( 'FREE', wc_price( $max_price ) );
                $price .= $product->get_price_suffix();
            } else {
                // 所有变体价格都是0
                $price = 'FREE';
            }
        }
    } 
    // 处理单个变体产品(选中后显示)
    elseif ( $product->is_type( 'variation' ) && 0 == $product->get_price() ) {
        $price = 'FREE';
    }
    // 处理简单产品
    elseif ( 0 == $product->get_price() ) {
        $price = '<span class="woocommerce-Price-amount amount">Contact us for a unique quote!</span>';
    }  
    
    return $price;
}

关键修改说明

  • 新增variation类型产品判断:用户选中单个零价格变体时,直接显示「FREE」
  • 优化可变产品判断逻辑:通过in_array检查是否存在零价格变体,覆盖所有含零价格的可变产品场景
  • 保留原简单产品的自定义文本逻辑,无需改动

内容的提问来源于stack exchange,提问作者Tamás Horváth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 22:17:35