mdkamrul
mdkamrul

Reputation: 274

Auto apply / remove a coupon code based on cart items in Woocommerce

I wanted to apply a coupon code to cart if cart have minimum 2 items. if not have then the coupon not will apply and show alter message and if have apply then will show a success message here is my code I have tried not working like I want

add_action( 'woocommerce_before_calculate_totals','conditionally_auto_add_coupon', 30, 1 );

function conditionally_auto_add_coupon( $cart ) {

    if ( is_admin() && !defined('DOING_AJAX') ) return; // Exit

    // HERE set the coupon code (in lowercase)
    $coupon_code = 'mycode';

    $total_item = 0;

    if (WC()->cart->has_discount('mycode')) {

        foreach( $cart->get_cart() as $cart_item ){
          $total_item++;
        }
        if($total_item < 2){
            $cart->remove_coupon( $coupon_code );

            wc_add_notice( __('you have only 1 item in cart'), 'alert');
        }
        else{
            $cart->add_discount( $coupon_code );

            wc_add_notice( __('coupon added'), 'notice');
        }
    }
}

Any help is welcome.

Upvotes: 4

Views: 2754

Answers (2)

Subair
Subair

Reputation: 91

Please use "Smart Coupon For Woocommerce" plugin implementing the auto coupon functionality,

Please refer this code in svn repo.

Upvotes: 0

LoicTheAztec
LoicTheAztec

Reputation: 254492

Try the following:

add_action( 'woocommerce_before_calculate_totals', 'auto_apply_coupon_conditionally', 10, 1 );
function auto_apply_coupon_conditionally( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $coupon_code = 'summer'; // HERE set the coupon code (in lowercase)
    $applied     = in_array( $coupon_code, $cart->get_applied_coupons() ) ? true : false;
    $item_count  = sizeof( $cart->get_cart() );
    $total_item  = 0;

    // Remove coupon
    if ( $item_count < 2 && $applied ) {
        $cart->remove_coupon( $coupon_code );
        wc_clear_notices();
        wc_add_notice( __('You have only 1 item in cart'), 'error');
    }
    // Add coupon
    elseif ( $item_count >= 2 && ! $applied ) {
        $cart->apply_coupon( $coupon_code );
        wc_clear_notices();
        wc_add_notice( __('A coupon has been added'), 'notice' );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works

Upvotes: 2

Related Questions