Prevent Product From Being Checked-Out Outside Of US

Happy New Year! Here is a quick snippet of code to prevent a product from being bought at your store from outside of the US or any other country you specify. Very useful in some situations and we use it often at work to do just that, preventing someone buying the product outside of the US or Canada.

add_action( 'woocommerce_before_checkout_process', 'prevent_product_checkout_except_north_america' );
function prevent_product_checkout_except_north_america() {

    // Product in Question
    $product_id = 563441;

    // The card doesn't have items that need shipping
    if( ! WC()->cart->needs_shipping() ) {
        return;
    }

    // Is the product even in the cart?
    $product_signature = WC()->cart->generate_cart_id( $product_id );
    if( ! WC()->cart->find_product_in_cart( $product_signature ) ) {
        return;
    }

    $eligible_shipping_countries = array( 'US', 'CA' );
    $shipping_country = isset( $_POST['shipping_country'] ) ? $_POST['shipping_country'] : $_POST['billing_country'];

    if( ! in_array( $shipping_country, $eligible_shipping_countries ) ) {
        wc_add_notice( 'Only customers from the US or Canada are eligible for this offer.', 'error' );
    }
}

That’s it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s