Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.