WooCommerce – Automatically Apply Coupon Code Based On State

Sep 28, 2021

WooCommerce – Automatically Apply Coupon Code Based On State


This post was originally created on our sister site WP Cover.
View Original Article
September 28, 2021

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.

Additional News

Perfect!

Let's get started. Fill out the form below to email us or request a call back.