Home > OS >  If coupon amount is higher than cart subtotal, also reduce the amount of shipping totals
If coupon amount is higher than cart subtotal, also reduce the amount of shipping totals

Time:03-09

The code is supposed to check if the fixed coupon amount is bigger than cart subtotals. If yes, subtract the remainder of the price from shipping totals. It's in my functions file.

add_filter('woocommerce_package_rates', 'custom_shipping_costs', 10, 2 );
function custom_shipping_costs( $rates, $package ){

//get the shipping total, cart subtotal and coupon amount
$dostava = $cart->shipping_total;
$iznos = $woocommerce->cart->get_cart_subtotal();
$kuponi = $woocommerce->cart->discount_total;

//subtract the coupon amount from cart subtotal
$razlika = $iznos - $kuponi;

//now check if it's higher than what's in the cart, if yes, set the new shipping costs
if($razlika < 0){
    $novadostava = $dostava - $razlika;
    $cart->shipping_total = $novadostava;
}

return $rates;
}

Unfortunately.. it doesn't work. Any suggestions?

CodePudding user response:

Here is an example since there are more to consider to it as taxes rates shipping methods if must define etc but current example works as it We have product that cost 18$ and coupon that discount 20$ with shipping tax 15$ at the end we get 13$ total - https://prnt.sc/365xV2BWx2wA

add_filter('woocommerce_package_rates', 'custom_shipping_costs');
function custom_shipping_costs( $rates ){

$cart = WC()->cart;
if($rates):
    foreach($rates as $rate_key => $rate):
        $dostava = $rate->get_cost();
    endforeach;
endif;
$iznos = $cart->subtotal;
$kuponi = $cart->get_coupons();
if($kuponi):
    foreach($kuponi as $kupon):
        $kuponi_amount = $kupon->get_amount();
    endforeach;
endif;

$razlika = $iznos - $kuponi_amount;
$razlika = abs($razlika);
if($razlika > 0){
    $novadostava = $dostava - $razlika;
    $rates[$rate_key]->cost = $novadostava;
}
return $rates;
}
  • Related