How to add shipping discount based on Coupon Discount Type

Knowledge Requirement:

You already read and understand how to make custom discount coupon type in Woocommerce or you can read from here.

Request:

My Client want to give shipping discount labeled with ‘Diskon Ongkir’ for his customer like image below:

Problem:

Coupon discount is can use for only cart and product

Question:

How to make it … ?

Reply:

We can add as negative fee, so open your functions.php in themes folder and add this code below:

function prefix_add_discount_line( $cart ) {

if(WC()->cart->shipping_total>0){
  if(WC()->cart->applied_coupons){
    foreach (WC()->cart->get_coupons() as $code => $coupon) { 
			
      if($coupon->discount_type=='diskon_ongkir'){
	 $diskon = $coupon->amount;
	 if($diskon>WC()->cart->shipping_total)
	    $diskon = WC()->cart->shipping_total;
	 
        $cart->add_fee(__( 'Diskon Ongkir', "woocommerce" ), -$diskon );
       }
     }
  }
 }
}
add_action( 'woocommerce_cart_calculate_fees', 'prefix_add_discount_line' );

Explanation:

  • WC()->cart->shipping_total is used for get shipping total
  • WC()->cart->applied_coupons is used to check is coupon has been inserted by us
  • WC()->cart->get_coupons() is used to get all coupon that already inserted by us
  • $coupon->discount_type==’diskon_ongkir’ is to check the type of discount

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *