Apply coupon on woocommerce price

To apply a coupon on a Woocommerce price programmatically use the following function.

<?php
/** 
 * Applies wc coupon on price
 */
function th_price_apply_coupon( $price, WC_Coupon $coupon ) {

   if ( ! $coupon ) return $price;

   $coupon_amount = $coupon->get_amount();
   $coupon_type   = $coupon->get_discount_type();

   if ( $coupon_type == 'percent' ) {
      $coupon_price = floatval( $price ) * ( ( 100 - $coupon_amount ) / 100 );
   } else {
      $coupon_price = floatval( $price ) - $coupon_amount;
   }
   return $coupon_price;
}
?>

I'm Robbert Vermeulen. I document everything I learn and help thousands of people with coding WordPress. My site has no ads or sponsors. If you enjoy my content, please consider supporting what I do.

Comments

    No comments yet..

Leave a reply

Feel free to ask questions or make comments.