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

调整WooCommerce简单商品优惠金额显示位置至价格下方

解决WooCommerce简单商品优惠金额显示位置问题

问题核心是简单商品使用的钩子优先级设置错误,导致优惠金额显示在标题上方而非价格下方。

原因分析

woocommerce_single_product_summary钩子的默认元素优先级规则如下:

  • 商品标题:优先级5
  • 商品价格:优先级10
  • 加入购物车按钮:优先级20

原代码中简单商品的函数优先级设为9,会在价格(优先级10)之前执行输出,若主题对钩子顺序有自定义调整,就会出现显示位置错误的情况。

修复方案

将简单商品的钩子优先级从9改为大于10的数值(比如11),确保优惠金额在价格之后输出:

// For simple products
add_action( 'woocommerce_single_product_summary', 'simple_product_saving_amount', 11 );
function simple_product_saving_amount() {
    global $product;

    if( $product->is_type('simple') && $product->is_on_sale() ) {
        $regular_price = (float) wc_get_price_to_display( $product, array('price' => $product->get_regular_price() ) );
        $active_price  = (float) wc_get_price_to_display( $product, array('price' => $product->get_sale_price() ) );

        $saved_amount  = $regular_price - $active_price;
        $percentage    = round( $saved_amount / $regular_price * 100 );

        echo '<p id="saving_total_price" style="
     font-size: 12px;
    text-align: center;
    width: 40%; 
    background: lightgoldenrodyellow;
    margin-bottom: 1em;
">'. __("You Save") .': ' . wc_price($saved_amount) . ' ('.$percentage.'%)</p>';
    }
}

// For product variations (on variable products)
add_filter( 'woocommerce_available_variation', 'variable_product_saving_amount', 12, 3 );
function variable_product_saving_amount( $data, $product, $variation ) {

    if( $variation->is_on_sale() ) {
        $saved_amount  = $data['display_regular_price'] - $data['display_price'];
        $percentage    = round( $saved_amount / $data['display_regular_price'] * 100 );

        $data['price_html'] .= '<p id="saving_total_price" style="
    font-size: 12px;
    text-align: center;
    width: 40%; 
    background: lightgoldenrodyellow;
    margin-bottom: 1em;
">'. __("You Save") .': ' . wc_price($saved_amount) . ' ('.$percentage.'%)</p>';

    }
    return $data;
}

补充说明

  • 优先级设为11后,函数会在价格元素(优先级10)执行完毕后输出,确保优惠金额显示在价格下方。
  • 若主题对woocommerce_single_product_summary的元素优先级有自定义调整,可根据实际情况微调数值(比如15),保证输出顺序符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 06:35:12