phpwordpresswoocommercecheckoutcity

Get cities as values and names for a custom checkout select field in Woocommerce


In woocommerce checkout I should need to set values of options in select field to be the city name and not a numbers (as shown in the screenshot below).

Here is a sample of my code:

 $option_cities = $wpdb->get_col( "SELECT name FROM $table_name" );
 $fields['billing']['billing_city']['type'] = 'select';
 $fields['billing']['billing_city']['options'] = $option_cities;

This is what I get:

enter image description here


Solution

  • Try the following using array_combine() to get the array values copied as keys in a new array:

     $cities = $wpdb->get_col( "SELECT name FROM $table_name" );
    
     $option_cities  = array_combine( $cities, $cities );
    
     $fields['billing']['billing_city']['type'] = 'select';
     $fields['billing']['billing_city']['options'] = $city_options;
    

    It should solve your problem…