By default, the City field in the WooCommerce Checkout is a regular text input. State/Province is a field that changes based on which country is selected. For some, it’s a dropdown, for others it’s a regular text input.
Let’s do the same for the City field.
The code in this file should be added in a separate plugin and activate it.
For the sake of keeping this tutorial short, we’ll have a function that will return just a few cities for 2 countries.
Data for Cities
In a real-world scenario, you could list everything in the function or have a database to manage such information.
We are using the country ISO code so we can easily find it when someone is choosing a different country. The value we get from the country dropdown will be the same ISO code.
Enqueueing the script and data
We check if we are on the checkout page.
If we are, we’ll enqueue the script and also the JSON object. With that, we will be able to get the cities by calling
Listening to Country Changes
To be able to change input field, we need to listen to the country dropdown. WooCommerce also triggers a
refresh event when the checkout page is loaded, so we can change it right after the page load.
That makes sense in case the initially selected country should have a city dropdown.
In this part, we’re collecting all data we need when such an event happens. That way we can create a different HTML element (input or select) and feed it the required data such as
id and similar.
We’re also finding the closest wrapper of the element we can find. That way, if only the shipping country has changed, we’ll target the shipping city dropdown, not the billing one.
Transforming the City Field
Let’s now transform the city field with the logic:
- if we have a country defined in the JSON, but no cities added, hide the field completely
- if we have a country defined and cities as well, create a dropdown field
- if we don’t have a country defined in the JSON, create a regular text field
After the field is created, add the attributes to it that we have saved and replace the old HTML with the new one.
Here you can download the code from this tutorial. The code is written in a single class and under a namespace to make it easier to manage it and change when needed.
Changing WooCommerce Checkout is a skill you’ll always need to keep up to date. And since WooCommerce has a lot of it made, you can sometimes just recreate what they’re already doing. Like in this tutorial, I actually copied their code for changing the state into different field and refactored it for cities.Become a Sponsor