基于重量的累进折扣显示剩余重量以获得更好的折扣信息

Weight based progressive discount displays remaining weight to get a better discount message

我正在使用 答案代码 (针对我之前的问题) 根据购物车总重量添加批量折扣。

代码是完美的,但我想在购物车页面(仅购物车)上方显示一个横幅,如 'Added to Cart' 消息,显示一条消息和客户必须为下一个订购更多的数量折扣规则。

示例消息:“如果您订购 10 欧元,- 额外您将获得 10% 的折扣”

我试图为消息框找到正确的代码,但找不到正确的代码。我只能找到 wc_add_to_cart_message_html,但我很确定这个不是正确的。

抱歉提出所有这些问题,但我是 PHP 的新手,想学习。 希望有人能帮忙。

已更新

您必须将所有相关代码替换为以下代码,该代码将根据购物车重量进行折扣,显示显示剩余重量的自定义消息以获得更好的百分比折扣(显示的百分比)。

For the message: As it's a weight based discount, it's not possible to display a remaining cost. Instead you can display the remaining weight required to get a better discount.

代码如下:

add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_discount', 30, 1 );
function shipping_weight_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $cart_weight   = $cart->get_cart_contents_weight();
    $cart_subtotal = $cart->get_subtotal(); // Or $cart->subtotal;
    $percentage    = 0;

    if ( $cart_weight >= 10 && $cart_weight < 30 ) 
    {
        $percentage       = 5;
        $remaining_weight = 30 - $cart_weight;
        $next_percent     = 7.5;
    } 
    elseif ( $cart_weight >= 30 && $cart_weight < 70 ) 
    {
        $percentage       = 7.5;
        $remaining_weight = 70 - $cart_weight;
        $next_percent     = 10;
    } 
    elseif ( $cart_weight >= 70 && $cart_weight < 130 ) 
    {
        $percentage       = 10;
        $remaining_weight = 130 - $cart_weight;
        $next_percent     = 12.5;
    } 
    elseif ( $cart_weight >= 130 && $cart_weight < 200 ) {
        $percentage       = 12.5;
        $remaining_weight = 200 - $cart_weight;
        $next_percent = 15;
    } 
    elseif ( $cart_weight >= 200 ) 
    {
        $percentage       = 15;
        $next_percent     = false;
    } 
    else 
    {
        $next_percent = 5;
        $remaining_weight = 10 - $cart_weight;
    }

    // Apply a calculated discount based on weight
    if( $percentage > 0 ) {
        $discount = $cart_subtotal * $percentage / 100;
        $cart->add_fee( sprintf( __( 'Weight %s discount', 'woocommerce' ), $percentage.'%'), -$discount );
    }

    if ( did_action( 'woocommerce_cart_calculate_fees' ) >= 2 )
        return;

    // Display a custom message
    if ( is_cart() && $next_percent ) { 
        wc_add_notice( sprintf( 
            __("If you order for %s extra, you will receive a %s discount.", "woocommerce"), 
            wc_format_weight($remaining_weight), $next_percent.'%'
        ), 'notice' );
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

购物车中显示的消息的屏幕截图: