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

WooCommerce单品页批量折扣价格显示异常(代码返回0)求助

解决WooCommerce单品页价格下方显示批量折扣价的问题

你的代码显示价格为0,核心原因是$product->get_regular_price()可能返回空值(比如商品未设置常规价格、$product对象未正确初始化),直接参与计算时被转为0。以下是修正后的极简实现代码:

// 在单品页价格下方添加批量折扣提示
function add_bulk_discount_text_under_price() {
    global $product;
    
    // 确保$product是有效的WooCommerce产品对象
    if ( ! $product instanceof WC_Product ) return;
    
    // 获取常规价格并转为浮点型,避免空值导致计算错误
    $regular_price = (float) $product->get_regular_price();
    
    // 无有效价格时直接返回
    if ( $regular_price <= 0 ) return;
    
    // 计算折扣价
    $discount_5 = $regular_price * 0.95;
    $discount_10 = $regular_price * 0.90;
    
    // 输出格式化后的折扣文本
    echo '<p class="bulk-discount-text">for 5 pieces: ' . wc_price($discount_5) . '</p>';
    echo '<p class="bulk-discount-text">for 10 pieces: ' . wc_price($discount_10) . '</p>';
}
// 钩子优先级设为20,确保在价格模块之后显示
add_action('woocommerce_single_product_summary', 'add_bulk_discount_text_under_price', 20);

关键修正说明

  • 增加$product instanceof WC_Product判断,避免对象未初始化导致的报错
  • 用(float)强制转换价格为浮点型,彻底解决空字符串/非数值导致的0值问题
  • 添加价格有效性校验,防止无价格商品输出无效内容
  • 类名调整为语义化的bulk-discount-text,方便后续自定义样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:54:57