Apply automatically a coupon based on specific cart items count in Woocommerce

前端 未结 1 833
后悔当初
后悔当初 2020-12-18 16:22

I am trying to automatically trigger a coupon to be applied in the cart specifically for when there are 4 items in the cart.

The coupon is pre-created in the Woocom

相关标签:
1条回答
  • 2020-12-18 16:59

    There is some little mistakes and errors in your code. Try the following instead:

    add_action( 'woocommerce_before_calculate_totals', 'auto_add_coupon_based_on_cart_items_count', 25, 1 );
    function auto_add_coupon_based_on_cart_items_count( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Setting and initialising variables
        $coupon = 'tasterbox'; // <===  Coupon code
        $item_count = 4; // <===  <===  Number of items
        $matched    = false;
    
        if( $cart->cart_contents_count >= $item_count ){
            $matched = true; // Set to true
        }
    
        // If conditions are matched add coupon is not applied
        if( $matched && ! $cart->has_discount( $coupon )){
            // Apply the coupon code
            $cart->add_discount( $coupon );
    
            // Optionally display a message
            wc_add_notice( __('TASTER BOX ADDED'), 'notice');
        }
        // If conditions are not matched and coupon has been appied
        elseif( ! $matched && $cart->has_discount( $coupon )){
            // Remove the coupon code
            $cart->remove_coupon( $coupon );
    
            // Optionally display a message
            wc_add_notice( __('SORRY, TASTERBOX NOT VALID'), 'error');
        }
    }
    

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

    0 讨论(0)
提交回复
热议问题