WP SITES

3085 Coded Tutorials & 287 Plugins

Custom Shipping Rates Per Zip Code in WooCommerce

This snippet enables you to set flat rate shipping based on zip or post code. It’s a very basic piece of code and very easy to use.

There’s 2 simple steps :

  1. All you need to do is set the flat rate shipping method for your shipping zone. In your WordPress Dashboard, Go to WooCommerce > Settings > Shipping, add or edit an existing zone and add a flat rate shipping method. If you set the cost to 0, any zip code not included in your code will be set to free shipping. If you add a cost, any postal code not set in the code will default to this cost.

2. Add your post codes with matching rates in the code.

Example :

'90210'  => 80,

In the above example, 90210 is the postal code and 80 is the flat rate for anyone with a shipping address matching that postal code. You can add unlimited postal codes with custom shipping rates.

Here’s the full code you can modify/extend in your child themes functions file or custom PHP code snippets plugin.

add_filter( 'woocommerce_package_rates', 'custom_shipping_rates_based_on_postcode_1_0_0', 10, 2 );
function custom_shipping_rates_based_on_postcode_1_0_0( $rates, $package ) {

    $postcode = WC()->customer->get_shipping_postcode();
    
    $custom_rates = array(
        '90210'  => 80,
        '90211'  => 100, 
    );

    foreach ( $rates as $rate_key => $rate ) {
    
        if ( isset( $custom_rates[ $postcode ] ) ) {
            $rates[ $rate_key ]->cost = $custom_rates[ $postcode ];
        }
    }

    return $rates;
}

Any postcodes not included will use the default cost set in the flat rate shipping method settings :

Prefer a non coded solution with .csv import option?

Checkout the extended version of this code.

Leave a Reply

New Plugins