0

On checkout page, I am trying to disable the shipping method option according to my area postcode. You can find image here . I am working on Wordpress and PHP as a backend.

If the postcode doesnot match the area, the shipping method will be disable and the text "" will be shown here. I am using this code:

        $packages = WC()->cart->get_shipping_packages();

        foreach ($packages as $key => $value) {
            $shipping_session = "shipping_for_package_$key";

            unset(WC()->session->$shipping_session);
        }

But this code is not working, It will not disable the shipping method option. Can anyone help me?

Mani
  • 43
  • 5

1 Answers1

0

You can disable shipping methods via the woocommerce_package_rates hook.

You can get the postcode via the second argument of the hook: $package.

In the example below, if the postcode doesn't match one of those in the $postcodes array, the shipping methods are disabled (you can also apply your logic in reverse, by exclusion. You can also check the state and country if needed.).

All the fields you can get through $package are:

  • $package['destination']['country']
  • $package['destination']['state']
  • $package['destination']['postcode']
  • $package['destination']['city']
  • $package['destination']['address']
  • $package['destination']['address_1']
  • $package['destination']['address_2']

Then:

// disable shipping methods based on postcode
add_filter( 'woocommerce_package_rates', 'disable_shipping_method_based_on_postcode', 10, 2 );
function disable_shipping_method_based_on_postcode( $rates, $package ) {

    // initialize postcodes to match
    $postcodes = array( 12050, 20052, 15600, 45063 );

    // if the customer's postcode is not present in the array, disable the shipping methods
    if ( ! in_array( $package['destination']['postcode'], $postcodes ) ) {
        foreach ( $rates as $rate_id => $rate ) {
            unset( $rates[$rate_id] );
        }
    }
 
    return $rates;
    
}

The code has been tested and works. Add it to your active theme's functions.php.

RELATED ANSWERS

Vincenzo Di Gaetano
  • 3,892
  • 3
  • 13
  • 32
  • Hi @Vincenzo, I can't use any hook to solve this. As I extended the plugin and getting the postcode from the Wordpress admin side shipping settings. I need to get shipping methods in that PHP file and unset it according to postcodes. Thank You. – Mani Apr 14 '21 at 00:00
  • Could you publish your complete code necessary to be able to test without using any hooks? I'll do some tests and let you know. Thank you. – Vincenzo Di Gaetano Apr 14 '21 at 07:24
  • Hi @Vincenzo, I have updated the question with my full function. I have to unset the shipping options when the status code of the API doesn't return the 200. Thank You – Mani Apr 14 '21 at 23:39