Remove specific WooCommerce shipping method depending on states

I came across the code below which looks like it should do what I want. Upon testing, however, it’s not working.

We need to get rid of 2nd day air shipping in certain states. For example, we are located in Pennsylvania, and if someone is buying from there, we don’t want that option to show.

add_filter( 'woocommerce_package_rates', 'unset_ups_shipping_rates_for_specific_states' , 10, 2 );
function unset_ups_shipping_rates_for_specific_states( $rates, $package ) {
    // Setup an array of states that do not allow UPS Shipping 2nd Day Air. As of 10/18/2015 we added 3 days ground too.
    $excluded_states = array( 'FL','AL','KY','LA','MS','TN','GA','SC','NC','KY','DC','VA','AR','CT','DE','IL','IN','KS','MA','ME','MD','MN','MI','MO','NH','NJ','NY','OH','OK','PA','RI','TX','VT','WV','WI' );
    foreach ( WC()->cart->get_shipping_packages() as $package ) {
        if( in_array( $package, $excluded_states ) ) :
            unset( $rates['sups:02:0'] ); // Unset 2-Day Air
            unset( $rates['ups:02'] );
            unset( $rates['sups:12:0'] ); // Unset 3-Day Select too
            unset( $rates['ups:12'] );
        else:
            unset( $rates['sups:03:0'] ); // Unset Ground
            unset( $rates['ups:03'] );
        endif;
    }
    // Return what's left of the $rates array
    return $rates;
}

How can I make this code work to unset specific shipping methods based on states?

Read more here: Remove specific WooCommerce shipping method depending on states

Leave a Reply

Your email address will not be published. Required fields are marked *