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

混江龙づ霸主 提交于 2021-02-04 19:15:38

问题


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:

Thanks


回答1:


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:

  • Customizing checkout fields using actions and filters - Overriding core fields



回答2:


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.



来源:https://stackoverflow.com/questions/39698585/change-town-city-text-field-to-select-option-field-in-checkout-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!