John Davidson

php - Woocommerce disable the shipping option methods in checkout

0 comments
Message:


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?



My Answer:
"Shipping method not available for this area" will be displayed instead.

Here is the code you can use in your functions.php file to achieve this:

php
add_filter( 'woocommerce_package_rates', 'disable_shipping_method_based_on_postcode', 10, 2 );

function disable_shipping_method_based_on_postcode( $rates, $package ) {
$postcode = WC()->customer->get_shipping_postcode();

// Check if postcode is in the restricted area
if ( $postcode != '12345' ) { // Replace '12345' with your restricted postcode
foreach( $rates as $rate_id => $rate ) {
// Disable the shipping method
unset( $rates[$rate_id] );
}

// Add a custom message
$rates['custom_message'] = array(
'id' => 'custom_message',
'label' => 'Shipping method not available for this area',
'cost' => 0
);
}

return $rates;
}


Make sure to replace '12345' with your actual restricted postcode. This code will disable all shipping methods and display a custom message if the postcode does not match the restricted area.

Rate this post

3 of 5 based on 3811 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us