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

WooCommerce促销商品价格前置自定义文本不生效问题求助

WooCommerce促销商品价格前置文本问题排查与解决方案

问题描述

需要为WooCommerce中处于促销状态的商品价格添加自定义前置文本:原价前显示「Regular Price: 」,促销价前显示「Final Price: 」。使用提供的代码后,仅促销价显示了对应文本,原价未添加前置文本,不符合预期。

问题原因

原代码通过str_replace替换现有HTML标签的方式添加文本,该逻辑过度依赖WooCommerce默认的价格HTML结构,一旦标签位置、包裹方式发生变化,替换就会失效。实际测试中,原代码的<del>标签替换未正确作用到原价前,导致前置文本未显示。

解决方案

直接获取商品的原价与促销价,手动构建符合需求的价格HTML结构,避免依赖默认输出的HTML标签,逻辑更稳定可靠。

修正后的代码:

function add_custom_text_before_sale_prices( $price, $product ) {
    // 定义前置文本
    $text_regular_price = __("Regular Price: ");
    $text_final_price = __("Final Price: ");

    if ( $product->is_on_sale() ) {
        // 获取并格式化原价与促销价
        $regular_price = wc_price( $product->get_regular_price() );
        $sale_price = wc_price( $product->get_sale_price() );
        
        // 构建自定义价格HTML结构
        $return_string = '<del>' . $text_regular_price . $regular_price . '</del><br>' . $text_final_price . '<ins>' . $sale_price . '</ins>';
        
        return $return_string;
    }
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'add_custom_text_before_sale_prices', 100, 2 );

代码说明

  • 直接调用$product->get_regular_price()和$product->get_sale_price()获取商品价格数据,避免解析HTML的不确定性
  • 使用wc_price()函数格式化价格,保证价格显示符合WooCommerce的货币设置
  • 手动拼接<del>(原价)和<ins>(促销价)标签及前置文本,确保输出结构完全符合需求

内容的提问来源于stack exchange,提问作者thecodedeveloper.com

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:39:26