Search code examples
phpwordpresswoocommercehook-woocommerce

Woocommerce do not apply coupon if subtotal below minimum amount


I have issue. I have coupon that give me 15% off. Also i have shipping method that works on minimum $200. I noticed if I apply coupon on amount ~ $200, subtotal goes under $200 and coupon shipping method worked. I am wondering to create a way to restrict smarter coupon to not be applied if subtotal goes below $200.

Code I am trying is:

add_action( 'woocommerce_before_cart' , 'home_test_coupon_fix' );
add_action( 'woocommerce_before_checkout_form' , 'home_test_coupon_fix' );
function home_test_coupon_fix() {
    $cart_total = WC()->cart->get_subtotal();
    $coupon_id = 'hometest';
    $minimum_amount = 200 + WC()->cart->get_coupon_discount_amount( 'hometest' );
    $currency_code = get_woocommerce_currency();
    wc_clear_notices();
    
    echo $minimum_amount;

    if ( $cart_total < $minimum_amount && $woocommerce->cart->applied_coupons === $coupon_id ) {
         WC()->cart->remove_coupon( 'hometest' );
         wc_print_notice( "Get 50% off if you spend more than $minimum_amount $currency_code!", 'notice' );
    } 
    wc_clear_notices();
}

Solution

  • There are some bugs in your code. first, you not declare global $woocommerce; into starting of your function. $woocommerce->cart->applied_coupons this will be array so you have to pass key to check hometest

    add_action( 'woocommerce_before_cart' , 'home_test_coupon_fix' );
    add_action( 'woocommerce_before_checkout_form' , 'home_test_coupon_fix' );
    
    function home_test_coupon_fix() {
        global $woocommerce;
        $cart_total     = WC()->cart->get_subtotal();
        $coupon_id      = 'hometest';
        $minimum_amount = 500 + WC()->cart->get_coupon_discount_amount( $coupon_id );
        $currency_code  = get_woocommerce_currency();
        wc_clear_notices();
        if ( $cart_total < $minimum_amount && $woocommerce->cart->applied_coupons[0] === $coupon_id ) {
            WC()->cart->remove_coupon( 'hometest' );
            wc_print_notice( "Get 50% off if you spend more than $minimum_amount $currency_code!", 'notice' );
        } 
        wc_clear_notices();
    }
    

    Updated as per OP request

    You can use the woocommerce_coupon_message filter hook to remove the coupon message.

    function remove_coupon_message( $msg, $msg_code, $this ){
        global $woocommerce;
        $cart_total     = WC()->cart->get_subtotal();
        $coupon_id      = 'hometest';
        $minimum_amount = 500 + WC()->cart->get_coupon_discount_amount( $coupon_id );
        $currency_code  = get_woocommerce_currency();
        wc_clear_notices();
        if ( $cart_total <= $minimum_amount && $woocommerce->cart->applied_coupons[0] === $coupon_id ) {
            return "";  
        }
        return $msg;
    }
    add_filter('woocommerce_coupon_message','remove_coupon_message', 10,3 );
    

    Tested and works.

    enter image description here