0

We want to give a discount based on the shipping cost to our customers (50% of the shipping cost). Below is the code to manipulate the discount, it's okay but I can't get the shipping cost. Tried php $current_shipping_cost = WC()->cart->get_cart_shipping_total(); but it does not return the correct value. Is there a way to do this?

function woocommerce_coupon_get_discount_amount($discount, $discounting_amount, $cart_item, $single, $coupon) { 

        if ($coupon->code == 'custom'){

            /*It is needed to know the shipping cost to calculate the discount. 
            $current_shipping_cost = WC()->cart->get_cart_shipping_total();
echo $current_shipping_cost; is not returning the correct value.
            */
             return $discount;
            }
        }
//add hook to coupon amount hook
add_filter('woocommerce_coupon_get_discount_amount', 'woocommerce_coupon_get_discount_amount', 100, 5);

3 Answers3

0

Use "woocommerce_after_calculate_totals" hook. It gives you cart object on checkout or cart page. You can get both shipping total and shipping tax total if your site using taxes.

$cart->shipping_total;
$cart->shipping_tax_total;
Logicfire
  • 101
  • 3
  • Can I modify the coupon amount in that hook? What I have found is that I can add a fee with `$cart->add_fee` but it is noted in the woo docs that negative amount should not be entered. – László T Jun 26 '19 at 10:11
  • You can add Negative fee but you have to keep check on Taxes. If price have additional taxes you have re-calculate those too. – Logicfire Jun 26 '19 at 11:13
0

@László T , you can use following code to get shipping cost. see code i have given 50% discount of the shipping cost. This is working for me.

function woocommerce_coupon_get_discount_amount($discount, $discounting_amount, $cart_item, $single, $coupon) {
    if ($coupon->code == 'ship_discount'){  // ship_discount is coupon code
        $shipping_cost = 0;
        foreach( WC()->session->get('shipping_for_package_0')['rates'] as $method_id => $rate ){
            $shipping_cost += $rate->cost; // calculate  shipping cost
        }
        return  $shipping_cost/2;  //shipping cost to calculate the discount
    }
}
add_filter('woocommerce_coupon_get_discount_amount', 'woocommerce_coupon_get_discount_amount', 10, 5);

I hope this may be helpful to you.

Thanks

Team Dolphin
  • 173
  • 7
0

This might help you out with discount.

add_action('woocommerce_cart_calculate_fees','woocommerce_discount_for_shipping' );
function woocommerce_discount_for_shipping()
{
    global $woocommerce;
    //$discount_cart = $cart->discount_cart;
    $shipping_including_tax = $woocommerce->cart->shipping_total + $woocommerce->cart->shipping_tax_total;
    $percentage = 0.5;
    $discount = $shipping_including_tax * $percentage;
    //var_dump($discount);
    $woocommerce->cart->add_fee('Shipping Discount:', -$discount, false);
}
Logicfire
  • 101
  • 3