Krusna
Krusna

Reputation: 33

Change town/city text field to Select Option field in checkout form

In Woocommerce, I would like to change Town/City text field in a select field option field.

What should i do?

Here is a screenshot:

enter image description here

Thanks

Upvotes: 3

Views: 5248

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 254373

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:

Upvotes: 3

Lax Mariappan
Lax Mariappan

Reputation: 146

You can customize the checkout fields by actions and filters.

Please refer the official documentation here

    // Add these code in your theme's function.php
add_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.

Upvotes: 2

Related Questions