Ferna
Ferna

Reputation: 97

Drop down of auto values country/state/city WooCommerce storefront

I am looking for a drop down of country/state/city. I am getting country state auto populated, but cities are not going through well. By default, I am able to get the countries.

// State-Country additions

/**
 * Code goes in functions.php or a custom plugin.
 */

add_filter('woocommerce_states', 'SA_woocommerce_states');

function SA_woocommerce_states($states) {
    $states['ZA'] = array(
        'EC' => __('Eastern Cape', 'woocommerce'),
    );
    return $states;
}

// Change "city" checkout billing and shipping fields to a dropdown

add_filter('woocommerce_checkout_fields', 'override_checkout_city_fields');

function override_checkout_city_fields($fields) {

    // Define here in the array your desired cities (Here an example of cities)
    $option_cities = array(
        '' => __('Select your city'),
        'a' => 'a',
    );

    $fields['billing']['billing_city']['type'] = 'select';
    $fields['billing']['billing_city']['options'] = $option_cities;
    $fields['shipping']['shipping_city']['type'] = 'select';
    $fields['shipping']['shipping_city']['options'] = $option_cities;

    return $fields;
}

Upvotes: 0

Views: 5761

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253886

With your actual code you are replacing all existing states of "South Africa" (ZA) by one state. So you are getting something like:

Enter image description here

To add this state you should need to change your code a little bit this way:

add_filter('woocommerce_states', 'sa_woocommerce_states');
add_filter('woocommerce_countries_allowed_country_states', 'sa_woocommerce_states');

function SA_woocommerce_states( $states ) {
    $states['ZA']['EC'] = __('Eastern Cape', 'woocommerce');
    return $states;
}

The code goes in the function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works. You will get that instead this time:

Enter image description here

Now to get the cities auto populated you should use this:

add_filter( 'woocommerce_default_address_fields', 'override_checkout_city_fields', 10, 1 );
function override_checkout_city_fields($fields) {

    // Define here in the array your desired cities (Here an example of cities)
    $option_cities = array(
        '' => __( 'Select your city' ),
        'a' => 'a',
    );

    $fields['city']['type'] = 'select';
    $fields['city']['options'] = $option_cities;

    return $fields;
}

The code goes in the function.php file of your active child theme (or theme) or also in any plugin file.

It was tested ad worked…

But you will not get cities by states as this is a real development and too broad for Stack Overflow

Upvotes: 1

Related Questions