Reputation: 639
I have created a Woocommerce coupon with a discount type set to fixed cart discount and an initial coupon amount.
I want the coupon to function in such a way that when the customer enters the coupon code the total discount is computed and is set as the coupon amount. I'm using the woocommerce_applied_coupon hook in the theme's function.php.
Here's how I coded:
add_action( 'woocommerce_applied_coupon', 'action_woocommerce_applied_coupon', 10, 3 );
function action_woocommerce_applied_coupon( $array, $int, $int ){
$total_discount = 0;
$wc = wc();//use the WC class
foreach($wc->cart->get_cart() as $cart_item){
//loop through each cart line item
$total_discount += ...; //this is where the total discount is computed
}
//use the WC_COUPON class
$wc_coupon = new WC_Coupon("coupon-code");// create an instance of the class using the coupon code
$wc_coupon->set_amount($total_discount);//set coupon amount to the computed discounted price
var_dump($wc_coupon->get_amount());//check if the coupon amount did update
}
The var_dump displayed the $total_discount. But when I checked on the Cart Totals, I still see the initial coupon amount as the discount.
How do I get to update the coupon amount and apply this as the discount to the cart totals?
Upvotes: 2
Views: 5469
Reputation: 11
Try this
add_action( 'woocommerce_before_calculate_totals', 'auto_add_coupons_total_based', 10, 1 ); function auto_add_coupons_total_based( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// HERE define your coupon code
$coupon_percent = 'xyz20'; # <=== <=== <=== <=== <=== <===
$coupon_fixed = 'fixedamount'; # <=== <=== <=== <=== <=== <=== <===
// Get cart subtotal
$subtotal = 0;
foreach($cart->get_cart() as $cart_item ){
$subtotal += $cart_item['line_subtotal'];
$subtotal += $cart_item['line_subtotal_tax']; // with taxes
}
//Set HERE the limit amount
$limit = 40; //without Tax
// Coupon type "percent" (less than 200)
if( $subtotal < 200 && ! $cart->has_discount( $coupon_percent ) ){
// If coupon "fixed amount" type is in cart we remove it
if( $cart->has_discount( $coupon_fixed ) )
$cart->remove_coupon( $coupon_fixed );
}
// Coupon type "fixed amount" (Up to 200)
if( $subtotal >= 200 && $cart->has_discount( $coupon_percent ) ) {
// If coupon "percent" type is in cart we remove it
if( $cart->has_discount( $coupon_percent ) )
$cart->remove_coupon( $coupon_percent );
// Apply the "fixed amount" type coupon code
$cart->add_discount( $coupon_fixed );
// Displaying a custom message
$message = __( "The total discount limit of $$limit has been reached", "woocommerce" );
wc_add_notice( $message, 'notice' );
}
}
Upvotes: 1