Skip to content

Instantly share code, notes, and snippets.

@xadapter
Forked from Nishadup/function.php
Last active March 12, 2020 10:11
Show Gist options
  • Save xadapter/afffd0f0f51ce084295140040c0c0006 to your computer and use it in GitHub Desktop.
Save xadapter/afffd0f0f51ce084295140040c0c0006 to your computer and use it in GitHub Desktop.
Snippet to restrict WooCommerce shipping methods based on the state and ZIP/Post code. Supports PluginHive Shipping Plugins: https://www.pluginhive.com/product-category/woocommerce-plugin/woocommerce-shipping/
add_filter('woocommerce_package_rates', 'wf_restrict_shipping_methods_based_on_state_and_zipcode', 10, 2);
function wf_restrict_shipping_methods_based_on_state_and_zipcode($available_shipping_methods, $package){
$destination = $package['destination'];
$dest_postcode = $destination['postcode'];
$dest_state = $destination['state'];
//Config this array with state code, zip code, and services you have to show.
$restrict_methods = array(
'CA'=> array(
//Show only UPS Ground for California have zip code start with 910
'910' => array(
'wf_shipping_ups:03',
),
//Show only UPS Ground and 3 Day Select for California have zip code start with 912
'912' => array(
'wf_shipping_ups:03',
'wf_shipping_ups:12',
),
),
// Show only Ground and 3 Day Select for everywhere in New York
'NY'=> array(
'*' => array(
'wf_shipping_ups:03',
'wf_shipping_ups:12',
),
),
);
foreach ($available_shipping_methods as $current_service => $value) {
if( !empty($restrict_methods[$dest_state]) ){
foreach ($restrict_methods[$dest_state] as $postcode => $services_arr) {
if( ( $postcode == '*' || strstr( (string)$dest_postcode, (string)$postcode ) ) && in_array($current_service, $services_arr) ){
unset($available_shipping_methods[$current_service]);
}
}
}
}
return $available_shipping_methods;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment