Ship a Category Only to Certain Countries
Stops checkout when the cart contains products from a restricted category, such as batteries or plants, and the shipping country is not on your allowed list.
Opens WPIDE on
Code
$wpide_restricted_cats = array( 'plants' ); // Category slugs.
$wpide_restricted_countries = array( 'GB', 'IE' ); // Countries these may ship to.
add_action( 'woocommerce_after_checkout_validation', function ( $data, $errors ) use ( $wpide_restricted_cats, $wpide_restricted_countries ) {
$country = ! empty( $data['ship_to_different_address'] ) ? ( $data['shipping_country'] ?? '' ) : ( $data['billing_country'] ?? '' );
if ( '' === $country || in_array( $country, $wpide_restricted_countries, true ) || ! WC()->cart ) {
return;
}
$names = array();
foreach ( WC()->cart->get_cart() as $item ) {
if ( has_term( $wpide_restricted_cats, 'product_cat', $item['product_id'] ) ) {
$names[] = $item['data']->get_name();
}
}
if ( $names ) {
$errors->add( 'shipping', sprintf( 'Sorry, we cannot ship %s to %s. Please remove it to continue.', esc_html( implode( ', ', array_unique( $names ) ) ), esc_html( WC()->countries->countries[ $country ] ?? $country ) ) );
}
}, 10, 2 );
Notes
Uses two-letter country codes, and the error message names the products that cannot be shipped.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.