Show/Hide specific shipping methods based on postcode and cart subtotal


I would like to show or hide specific shipping options based on postcode and cart subtotal amount.
Here is my code:

add_filter( 'woocommerce_package_rates', 'unset_shipping_when_free_is_available', 10, 2 );
function unset_shipping_when_free_is_available( $rates, $package ) {
     $excluded_postcode = array( 1000,1030,1040,1050,1060,1070,1080,1081,1082,1083,1090,1140,1150,1160,1170,1180,1190,1200,1210 );
    if(WC()->cart->get_cart_subtotal() >= '50' && !in_array(WC()->customer->get_shipping_postcode(), $excluded_postcode )){
        if ( isset( $rates['free_shipping:4'] ) ) {
            unset( $rates['flat_rate:2'] );
            unset( $rates['flat_rate:26'] );
            unset( $rates['flat_rate:27'] );
    }elseif(WC()->cart->get_cart_subtotal() >= '50' && in_array(WC()->customer->get_shipping_postcode(), $excluded_postcode )){
        if ( isset( $rates['free_shipping:16'] ) ) {
            unset( $rates['flat_rate:13'] );
            unset( $rates['flat_rate:28'] );
            unset( $rates['flat_rate:29'] );
    return $rates;

What I want to do is when the customer’s postcode meets one of the list: array $excluded_postcode(Brussels’s postcode), there will be 2 options: free collective shipping(free_shipping:16) (the customer need to choose a date) or flat rate based on weight, but if the cart subtotal is >=50€, then the shipping fee will be free, there will be also 2 options (both free), one is free collective shipping (need to choose a date) and the other is free shipping when the minimum amount is 50€(free_shipping:4); if the customer’s postcode is different from the array (not from Brussels), the shipping rate is based on weight, but if the subtotal amount is >=50€, then it will be free shipping. So if subtotal greater or equals 50€, only free options will be shown (if postcode=Brussels, 2 free shipping options: free_shipping:4 and free_shipping:16, if not Brussels: only free_shipping:4), if subtotal less than 50€, 2 options if Brussels: free_shipping:16 and flat rate based on weight, if not Brussels: only flat rate based on weight.
(Brussels flat rates: flat_rate:2=0-2kg, flat_rate:26=2-5kg, flat_rate:27=5-10kg,
No Brussels flat rates: flat_rate:13=0-2kg, flat_rate:28=2-5kg, flat_rate:29=5-10kg)

It works fine except when the subtotal is less than 50€ and from Brussels, only one free shipping option is showing: free_shipping:16, I would like to have both free options to be displayed.

This is the checkout page:

I would be greatful if you could help me with this, thank you!

Y L 2 years 2020-11-02T13:10:20-05:00 0 Answers 11 views 0

Leave an answer