Halloween Sale 15% off Ends in See the plans
PHP

Offer a Shipping Method Only to Listed Postcodes

Shows a method such as local delivery or same-day courier only when the shipping postcode matches your list or starts with one of your prefixes.

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

Code

$wpide_local_rate_id   = 'flat_rate:3';                    // Rate ID to restrict.
$wpide_local_postcodes = array( '10115', '10117', '101*' ); // Exact postcodes or prefixes ending in *.

add_filter( 'woocommerce_package_rates', function ( $rates, $package ) use ( $wpide_local_rate_id, $wpide_local_postcodes ) {
    if ( ! isset( $rates[ $wpide_local_rate_id ] ) ) {
        return $rates;
    }

    $postcode = strtoupper( str_replace( ' ', '', (string) ( $package['destination']['postcode'] ?? '' ) ) );
    $allowed  = false;

    foreach ( $wpide_local_postcodes as $rule ) {
        $rule = strtoupper( str_replace( ' ', '', $rule ) );

        if ( '*' === substr( $rule, -1 ) ? 0 === strpos( $postcode, rtrim( $rule, '*' ) ) : $postcode === $rule ) {
            $allowed = true;
            break;
        }
    }

    if ( '' === $postcode || ! $allowed ) {
        unset( $rates[ $wpide_local_rate_id ] );
    }

    return $rates;
}, 20, 2 );

Notes

Use the rate ID shown in WooCommerce > Settings > Shipping (for example flat_rate:3); postcodes ending in * match by prefix.

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.