Shipping restrictions with WooCommerce variable products

This is something complicated… What you could do instead is to check cart items for allowed shipping countries, displaying an error notice and avoiding checkout when the customer country doesn’t match with the allowed country for all other product variations.

Below define the allowed shippable Variation ID (international) and the allowed base country code for your other product variations:

add_action( 'woocommerce_check_cart_items', 'check_cart_items_for_shipping' );
function check_cart_items_for_shipping() {
    $allowed_variation_id = '513'; // Here defined the allowed Variation ID
    $allowed_country      = 'US'; // Here define the allowed shipping country for all variations

    $shipping_country = WC()->customer->get_shipping_country();
    $countries        = WC()->countries->get_countries();

    // Loop through cart items
    foreach(WC()->cart->get_cart() as $cart_item ) {
        // Check cart item for defined product Ids and applied coupon
        if( $shipping_country !== $allowed_country && $cart_item['variation_id'] !== $allowed_variation_id ) {
            wc_clear_notices(); // Clear all other notices

            // Avoid checkout displaying an error notice
            wc_add_notice( sprintf( __('The product "%s" can not be shipped to %s.'),
                $cart_item['data']->get_name(),
                $countries[$shipping_country]
            ), 'error' );
            break; // stop the loop
        }
    }
}

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

enter image description here

Leave a Comment