Change town/city text field to Select Option field in checkout form
You need first to change the field type
from 'text' to 'select' using the dedicated hook woocommerce_default_address_fields
. Then you have also to change the label
and to and an options
argument where you are going to set your towns in an array of key/values
.
In this array, you will have a line by town separated by a coma.
Here is the code:
add_filter( 'woocommerce_default_address_fields' , 'customize_checkout_city_field' );function customize_checkout_city_field( $address_fields ) { // Set HERE the cities (one line by city) $towns_cities_arr = array( '0' => __('Select your city', 'my_theme_slug'), 'paris' => 'Paris', 'versailles' => 'Versailles', 'cannes' => 'Cannes', ); // Customizing 'billing_city' field $address_fields['city']['type'] = 'select'; $address_fields['city']['class'] = array('form-row-last', 'my-custom-class'); // your class here $address_fields['city']['label'] = __('Town / city', 'my_theme_slug'); $address_fields['city']['options'] = $towns_cities_arr; // Returning Checkout customized fields return $address_fields;}
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
The code is tested and fully functional.
Update: To add your custom class, replace in $address_fields['city']['class']…
the class 'my-custom-class'
by yours.
References:
You can customize the checkout fields by actions and filters.
Please refer the official documentation here
// Add these code in your theme's function.phpadd_filter( 'woocommerce_default_address_fields' , 'custom_override_default_address_fields' );// Our hooked in function - $address_fields is passed via the filter!function custom_override_default_address_fields( $fields) {$fields['billing']['your_field']['options'] = array( 'option_1' => 'Option 1 text', 'option_2' => 'Option 2 text'); return $fields;}
In case you are looking for a plugin you can use checkout field editor from woocommerce team.