Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of restricting shipping to a single state for a single shipping class with WooCommerce, prepared for Evan Thorpe based on my blog post http://stevegrunwell.com/blog/woocommerce-restrict-shipping
public function is_available( $package ) {
// Determine if we have any items in the "In-state" shipping class
$restricted_shipping_class_slug = 'in-state';
$permitted_states_for_restricted_items = array( 'NY' );
$has_restricted_items = false;
foreach ( $package as $pkg ) {
if ( isset( $pkg['contents'] ) ) {
foreach ( $pkg['contents'] as $contents ) {
if ( isset( $contents['data'] ) && $contents['data']->get_shipping_class() == $restricted_shipping_class_slug ) {
$has_restricted_items = true;
break;
}
}
}
}
// Limit items in the "In-state" shipping class to $permitted_states_for_restricted_items
if ( $has_restricted_items && ! in_array( $package['destination']['state'], $permitted_states_for_restricted_items ) ) {
return false;
// The states/territories not permitted for this method
$restricted = array( 'AK', 'AS', 'GU', 'HI', 'MP', 'PR', 'UM', 'VI' );
} elseif ( in_array( $package['destination']['state'], $restricted ) ) {
return false;
}
return parent::is_available( $package );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment