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

WooCommerce:将0售价替换为自定义文本并保留原价删除线

解决WooCommerce 0元售价替换为自定义文本并保留原价删除线的问题

原代码的问题在于使用了wc_format_price_range函数,该函数用于生成价格区间格式,而非WooCommerce默认的促销价(原价+售价)结构,导致原价丢失删除线样式。以下是两种可行的修改方案:

方案一:复用默认促销价格结构

利用WooCommerce内置函数生成带删除线的原价HTML,再替换售价部分为自定义文本:

function my_wc_custom_get_price_html( $price, $product ) {
    // 仅处理售价为0的产品
    if ( $product->get_price() == 0 ) {
        // 产品有原价且处于促销状态
        if ( $product->is_on_sale() && $product->get_regular_price() ) {
            // 生成默认促销价格HTML(含删除线原价)
            $regular_price_html = wc_format_sale_price(
                wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ),
                ''
            );
            // 替换售价部分为自定义文本
            $price = str_replace(
                '<ins><span class="amount"></span></ins>',
                '<ins><span class="amount">' . __( 'Free for members!', 'woocommerce' ) . '</span></ins>',
                $regular_price_html
            );
        } else {
            // 无原价时直接显示自定义文本
            $price = '<span class="amount">' . __( 'Free for members!', 'woocommerce' ) . '</span>';
        }
    }

    return $price;
}
add_filter( 'woocommerce_get_price_html', 'my_wc_custom_get_price_html', 10, 2 );

方案二:手动构建默认价格HTML结构

直接按照WooCommerce默认的价格DOM结构编写,确保样式与系统一致:

function my_wc_custom_get_price_html( $price, $product ) {
    if ( $product->get_price() == 0 ) {
        if ( $product->is_on_sale() && $product->get_regular_price() ) {
            $regular_price = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );
            // 构建带删除线原价+自定义售价的结构
            $price = sprintf(
                '<p class="price"><del><span class="amount">%s</span></del> <ins><span class="amount">%s</span></ins></p>',
                wc_price( $regular_price ),
                __( 'Free for members!', 'woocommerce' )
            );
        } else {
            $price = '<p class="price"><span class="amount">' . __( 'Free for members!', 'woocommerce' ) . '</span></p>';
        }
    }
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'my_wc_custom_get_price_html', 10, 2 );

说明

两种方案都保留了WooCommerce默认的价格样式类(price、del、ins、amount),确保删除线等样式正常显示,同时将0元售价替换为指定的自定义文本。

内容的提问来源于stack exchange,提问作者Menfesawi Simon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:37:29