111
WooCommerce allows you to limit shipping by countries (or “allowed” countries). However, say your business is based in Pennsylvania, USA (PA) or in one of the Australian states. You may want to limit shipping to a state only.
All you need is pasting the following code in your functions.php
WooCommerce: limit shipping to only 1 state
/** * @snippet Only ship to PA * @how-to Get tutoraspire.com FREE * @sourcecode https://tutoraspire.com/?p=309 * @author Tutor Aspire * @testedwith WooCommerce 3.2.1 */ function tutoraspire_only_ship_to_pa( $rates, $package ) { global $woocommerce; $excluded_states = array( 'AL','AK', 'AS','AZ','AR','CA','CO','CT','DE', 'DC','FL','FM','GA','GU','HI','ID', 'IL','IN','IA','KS','KY','LA','ME', 'MH','MD','MA','MI','MN','MS','MO', 'MT','NE','NV','NH','NJ','NM','NY', 'NC','ND','MP','OH','OK','OR','PW', 'PR','RI','SC','SD','TN','TX','UM', 'UT','VT','VA','VI','WA','WV','WI', 'WY' ); if( in_array( WC()->customer->get_shipping_state(), $excluded_states ) ) { $rates = array(); } return $rates; } add_filter( 'woocommerce_package_rates', 'tutoraspire_only_ship_to_pa', 10, 2 );
WooCommerce 2.1+ Snippet
woocommerce_available_shipping_methods has been replaced with woocommerce_package_rates.
If you’re targeting a different country, you will need to take a look at the woocommercei18nstates.php folder inside the plugin, and then find your desired country. If states are not there, please check https://docs.woocommerce.com/document/states-not-in-core/.
/** * @snippet Only ship to PA WooCommerce 2.1+ * @how-to Get tutoraspire.com FREE * @sourcecode https://tutoraspire.com/?p=309 * @author Tutor Aspire * @testedwith WooCommerce 2.6 */ function tutoraspire_only_ship_to_pa( $rates, $package ) {global $woocommerce; $excluded_states = array( 'AL','AK', 'AS','AZ','AR','CA','CO','CT','DE', 'DC','FL','FM','GA','GU','HI','ID', 'IL','IN','IA','KS','KY','LA','ME', 'MH','MD','MA','MI','MN','MS','MO', 'MT','NE','NV','NH','NJ','NM','NY', 'NC','ND','MP','OH','OK','OR','PW', 'PR','RI','SC','SD','TN','TX','UM', 'UT','VT','VA','VI','WA','WV','WI', 'WY' ); if( in_array( WC()->customer->shipping_state, $excluded_states ) ) { $rates = array(); } return $rates; } add_filter( 'woocommerce_package_rates', 'tutoraspire_only_ship_to_pa', 10, 2 );
Up to WooCommerce 2.0
// Only ship to PA Woo 2.0 function only_ship_to_pa( $available_methods ) { global $woocommerce; $excluded_states = array( 'AL','AK', 'AS','AZ','AR','CA','CO','CT','DE', 'DC','FL','FM','GA','GU','HI','ID', 'IL','IN','IA','KS','KY','LA','ME', 'MH','MD','MA','MI','MN','MS','MO', 'MT','NE','NV','NH','NJ','NM','NY', 'NC','ND','MP','OH','OK','OR','PW', 'PR','RI','SC','SD','TN','TX','UM', 'UT','VT','VA','VI','WA','WV','WI', 'WY' ); if( in_array( $woocommerce->customer->get_shipping_state(), $excluded_states ) ) { // Empty the $available_methods array $available_methods = array(); } return $available_methods; } add_filter( 'woocommerce_available_shipping_methods', 'only_ship_to_pa', 10 );