Skip to content

Instantly share code, notes, and snippets.

@xadapter
Last active March 13, 2020 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xadapter/3abd0560ca8dd3c5b65e3f48affa0b50 to your computer and use it in GitHub Desktop.
Save xadapter/3abd0560ca8dd3c5b65e3f48affa0b50 to your computer and use it in GitHub Desktop.
Snippet to filter WooCommerce shipping methods based on the state. Supports PluginHive Shipping Plugins: https://www.pluginhive.com/product-category/woocommerce-plugin/woocommerce-shipping/
add_filter( 'woocommerce_package_rates', 'xa_show_shipping_method_based_on_state', 10, 2 );
function xa_show_shipping_method_based_on_state( $available_shipping_methods, $package ) {
$states_list = array( 'AK', 'HI', 'PR', 'GU', 'AS', 'VI', 'UM' );
$eligible_services_for_states_list = array(
'wf_shipping_usps:flat_rate_box_priority',
'wf_shipping_usps:flat_rate_box_express',
'wf_shipping_usps:D_FIRST_CLASS',
'wf_shipping_usps:D_EXPRESS_MAIL',
'wf_shipping_usps:D_STANDARD_POST',
'wf_shipping_usps:D_MEDIA_MAIL',
'wf_shipping_usps:D_LIBRARY_MAIL',
'wf_shipping_usps:D_PRIORITY_MAIL',
'wf_shipping_usps:I_EXPRESS_MAIL',
'wf_shipping_usps:I_PRIORITY_MAIL',
'wf_shipping_usps:I_GLOBAL_EXPRESS',
'wf_shipping_usps:I_FIRST_CLASS',
'wf_shipping_usps:I_POSTCARDS',
);
// Basically, below code will reset shipping services if the shipping
// state is other than defined states_list.
if ( !in_array(WC()->customer->shipping_state, $states_list) ) {
foreach ( $eligible_services_for_states_list as &$value ) {
unset( $available_shipping_methods[$value] );
}
}
return $available_shipping_methods;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment