WooCommerce – Automatically Apply Coupon Code Based On State


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







WooCommerce – Automatically Apply Coupon Code Based On State

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' );
    }
}

Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!