View Original Article
add_action( 'woocommerce_before_calculate_totals', 'auto_apply_coupon_conditionally', 10, 1 ); function auto_apply_coupon_conditionally($cart) { //$cart = WC()->cart; if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return; $coupon_code = 'georgia10'; // HERE set the coupon code (in lowercase) $applied = in_array( $coupon_code, $cart->get_applied_coupons() ) ? true : false; $state_code = 'GA'; // Remove coupon if( 'GA' !== WC()->customer->get_billing_state() ){ $cart->remove_coupon( $coupon_code ); wc_clear_notices(); //wc_add_notice( __('Coupon code only valid on Georgia'), 'error'); } // Add coupon elseif ( 'GA' == WC()->customer->get_billing_state() && ! $applied ) { $cart->apply_coupon( $coupon_code ); wc_clear_notices(); wc_add_notice( __('A coupon has been added'), 'notice' ); } }
The post WooCommerce – Automatically Apply Coupon Code Based On State appeared first on WP Cover.