Updated Woommerce Cart Total Discount Total Not Updating The Order Saved

Viewed 208

I want to set max. Coupon discount for percent type, e.g 15% from total Order but max. $150. I have successfully updated this to my Cart, so it shows $150 max. But upon saved, the Order does not take the $150 but it recalculates the total Order x 15% and ignore the discount I have set on my Cart (which was $150).

Below is the code I use:

/**
 * Update subtotal with max discount set previously
 * @return string Subtotal with currency
 */
add_filter( 'woocommerce_cart_subtotal', 'woocommerce_set_max_discount', 10, 3 );
function woocommerce_set_max_discount( $subtotal, $compound, $cart ) {
    // Get current Coupons
    $coupons = $cart->coupon_discount_totals;
    foreach($coupons as $coupon_code => $discount) {
        $coupon = new WC_Coupon($coupon_code);
        // Check max discount
        $max_discount = get_post_meta( $coupon->get_id(), '_max_discount', true );
        if($max_discount) {
            // Current discount > max discount
            if($discount > $max_discount) {
                // Set discount to max discount
                $coupons[$coupon_code] = $max_discount;
                $need_update = true;
            }
        }
    }
    // Get total discount
    $total_discount = 0;
    foreach($coupons as $coupon_code => $discount) {
        $total_discount += $discount;
    }
    $total_content = $cart->get_subtotal() - $total_discount;
    // Update Cart's data
    // $cart->set_applied_coupons($coupons);
    $cart->set_discount_total($total_discount);
    $cart->set_cart_contents_total($total_content);
    $cart->set_total( $cart->get_subtotal() - $total_discount + $cart->get_fee_total());
    $cart->coupon_discount_totals = $coupons;
    return $subtotal;
}
0 Answers
Related