【问题标题】:Update cart fee on shipping method change in WooCommerce在 WooCommerce 中更新运输方式更改的购物车费用
【发布时间】:2021-08-09 07:25:04
【问题描述】:

我需要一种方式来提供最高 25 美元的运费折扣。我正在使用费用 API 来执行此操作,因为没有用于运输的优惠券代码。这是我的代码:

add_action( 'woocommerce_cart_calculate_fees', 'conditional_shipping_discount' );
  
function conditional_shipping_discount() {
    
    $max_shipping_discount = 25;
    $cart_subtotal = WC()->cart->subtotal;
    $current_shipping_method = WC()->session->get( 'chosen_shipping_methods' );
    $current_shipping_method_cost = WC()->session->get('cart_totals')['shipping_total'];
    
    // If our cart is > $99 AND shipping is not already free
    if ( ($cart_subtotal >= 99) && ($current_shipping_method_cost > 0) ) {
        
        // Calculate 25% of cart subtotal
        $calculated_shipping_discount = $cart_subtotal * 0.25; 
        
        // $shipping_discount = lowest value
        $shipping_discount = min( $current_shipping_method_cost, $calculated_shipping_discount, $max_shipping_discount );
                
        WC()->cart->add_fee( 'Shipping Discount', -1 * abs($shipping_discount) );
    }
}

这在大多数情况下都非常有效,除非客户选择了不同的运输方式。该费用仅显示先前选择的运费折扣。这张 GIF 说明了我的意思:

在重新加载页面或通过更改商品数量或更新结帐字段触发update_checkout 事件时更正费用。

如何在选择送货方式后立即更新购物车费用(送货折扣)?提前谢谢你。

【问题讨论】:

    标签: wordpress woocommerce


    【解决方案1】:

    在我检查您的功能时,如果我切换/更改运输方式,我们总是会收到以前的运输费用。 $current_shipping_method_cost 只有一个问题。

    所以如果你改变 1 行

    $current_shipping_method_cost = WC()->session->get('cart_totals')['shipping_total'];
    

    $current_shipping_method_cost = WC()->cart->get_shipping_total();
    

    您总是会收到当前/有效的运费。

    完整代码是:

    add_action( 'woocommerce_cart_calculate_fees', 'conditional_shipping_discount' );  
    function conditional_shipping_discount() {
    
        $max_shipping_discount = 25;
        $cart_subtotal = WC()->cart->subtotal;
    
        //$current_shipping_method = WC()->session->get( 'chosen_shipping_methods' );
        $current_shipping_method_cost = WC()->cart->get_shipping_total();
    
        // If our cart is > $99 AND shipping is not already free
        if ( ($cart_subtotal >= 99) && ($current_shipping_method_cost > 0) ) 
        {
           // Calculate 25% of cart subtotal
           $calculated_shipping_discount = $cart_subtotal * 0.25; 
        
           // $shipping_discount = lowest value
           $shipping_discount = min( $current_shipping_method_cost, $calculated_shipping_discount, $max_shipping_discount );
                
           WC()->cart->add_fee( 'Shipping Discount', -1 * abs($shipping_discount) );
        }
      }
    

    【讨论】:

    • 非常感谢。这绝对有效。我需要更好地理解 session() 和 cart()。
    • 很高兴为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-11-28
    • 2018-02-05
    • 2019-08-12
    • 1970-01-01
    • 2019-09-16
    • 2017-01-18
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多