How to restrict City and State on WooCommerce checkout

One of my recent WooCommerce projects was creating a cash-on-delivery system for a local business and they wanted to restrict the delivery address to their city and state. It’s easy to fill in a default value for City using a bit of JavaScript since it’s a text input but it’s important to validate the input on order submission because it’s easy to manipulate JS-filled values on the front end. Here’s how you would validate the billing city after order submission. Assume that we restricted front-end input for billing city to “Milan”.

				
					add_action( 'woocommerce_after_checkout_validation', 'custom_check_city_entered',10,2 );
function custom_check_city_entered($data,$errors){
    if($data['billing_city'] !== 'Milan'){
        $errors->add( 'billing', __( "We only deliver to Milan for now.", 'woocommerce' ) );
    }
}
				
			

We use the ‘woocommerce_after_checkout_validation’ hook to check if the entered city matches our local city and if not we throw an error. You can also use PHP’s in_array method to check against multiple city values.

Restricting by the state is even easier by using the ‘woocommerce_states’ filter. Here’s how you will restrict the states/provinces to Italy’s Milano province.

				
					add_filter( 'woocommerce_states', 'custom_limit_states' );
function custom_limit_states(){
    return array(
        'IT' => array( 
            'MI' => __( 'Milano', 'woocommerce' ),
        ),
    );
}
				
			

If you’re wondering how to find the keys like “MI” for Milano and “IT” for Italy, look under the states.php that comes bundled with WooCommerce plugin. The exact path is “wp-content/plugins/woocommerce/i18n/states.php”. Happy hunting and if you need help with your projects, feel free to hire me or hundreds of other freelancers like me on Codeable (link in the footer).

Leave a Comment