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

WooCommerce单品页加购按钮价格显示需求及错误代码修复求助

修复WooCommerce单品页加入购物车按钮价格显示问题

原代码存在以下致命错误导致网站崩溃:

  • 全局变量声明为$product,但代码中错误使用了$_product,变量名不匹配导致调用产品方法失败
  • woocommerce_price()函数已被WooCommerce弃用,需替换为wc_price()
  • 未判断产品是否处于促销状态,非促销产品会出现价格显示异常
  • 直接在__()函数中拼接变量,不符合国际化规范且可能导致文本格式混乱

修复后的代码如下:

add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_single_add_to_cart_with_prices' );
function custom_single_add_to_cart_with_prices( $text ) {
    global $product;

    // 仅在产品处于促销状态时修改按钮文本
    if ( $product->is_on_sale() ) {
        $regular_price = wc_price( $product->get_regular_price() );
        $sale_price = wc_price( $product->get_sale_price() );
        
        // 给常规价格添加删除线样式
        $formatted_regular_price = '<del>' . $regular_price . '</del>';
        
        // 拼接按钮文本,保留原"加入购物车"文本并添加价格
        $text = sprintf( __( 'Add to cart %s %s', 'woocommerce' ), $formatted_regular_price, $sale_price );
    }

    return $text;
}

说明:

  • 仅当产品处于促销状态时,才会在加入购物车按钮后显示划掉的常规价格和折扣价格
  • 使用wc_price()确保价格格式符合WooCommerce的设置(如货币符号、小数位数)
  • 用<del>标签给常规价格添加删除线,符合视觉上的折扣标识
  • 使用sprintf()配合__()函数,保证文本的可翻译性
  • 变量名统一使用$product,避免变量未定义错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:45:47