Search code examples
phpwoocommercecartcoupondiscount

Fix maximum coupon Discount On Cart percentage in WooCommerce


I have a coupon code (XYZ25) in woocommerce which include 25% off and maximum discount is Rs.250.

How can i restrict user's to not get more than Rs.250 Discount if they apply coupon code XYZ25 for 25% discount.


Solution

  • Since Woocommerce 3.2 or 3.3, this code doesn't work anymore

    1. You could set an additional coupon FIX250 code based on a fixed cart discount of **RS.250 (without tax) and with a Minimun spend of (4 x 250) = RS.1000.

    2. Then with the help of the script below, if customer apply your XYZ25 coupon code and if the cart total is up to Rs.1000, it will replace XYZ25 coupon by FIX250 displaying at the same time an explicative notice…

    Here is that code:

    add_action( 'woocommerce_calculate_totals', 'coupon_discount_max_switch', 10, 1);
    function coupon_discount_max_switch( $cart_obj ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Set HERE your 2 coupons slugs  <===  <===  <===  <===  <===  <===  <===  <===  <===
        $coupon_25_percent = 'xyz25';
        $coupon_25_fixed = 'fix250';
    
        // Set HERE the limit amount  <===  <===  <===  <===  <===  <===  <===  <===  <===  <===
        $limit = 250; // Without VAT
    
        $total_discount = $cart_obj->get_cart_discount_total(); // Total cart discount
    
        // When 'xyz25' is set and the total discount is reached
        if( $cart_obj->has_discount( $coupon_25_percent ) && $limit_icl_vat <= $total_discount ){
            // Remove the 'xyz25' coupon
            $cart_obj->remove_coupon( $coupon_25_percent );
            // Checking that the fixed dicount is not already set.
            if( ! $cart_obj->has_discount( $coupon_25_fixed ) ){
                // Add the 'fix250' coupon
                $cart_obj->add_discount( $coupon_25_fixed );
    
                // Displaying a custom message
                $message = __( "The cart discount limit of Rs.$limit is reached", "woocommerce" );
                wc_add_notice( $message, 'notice' );
            }
        } 
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    This working code is tested on WooCommerce versions 2.6.x and 3.0+.