1
votes

Im using woocommerce. On cart page there is a shipping calculator. I want to set my own state in the state/country drop down field. I want it to be pre-set automatically when someone comes on cart page. Check this pic

I found this hook and i think it can be used here but i don't know how to use it

function custom_woocommerce_calculated_shipping(){ 
    // Do something here
} 

add_action('woocommerce_calculated_shipping', 'custom_woocommerce_calculated_shipping');
1
Some feed back on the answer below will be highly appreciated please.LoicTheAztec

1 Answers

1
votes

The hook woocommerce_calculated_shipping will not be useful to define (restrict to) specific states for a specific country.

As the states for United Arab Emirates (AE) aren't defined in WooCommerce, you will need to:

  1. set the state field for "AE" country as a mandatory dropdown field,
  2. define all states for "AE" country in an array of a state codes and state label names pairs (caution as the state codes need to be in upper case western characters).

The code:

// Define all states For "AE" (United Arab Emirates)
add_filter( 'woocommerce_states', 'custom_uae_states', 10, 1 );
add_filter( 'woocommerce_countries_allowed_country_states', 'custom_uae_states', 10, 1 );
function custom_uae_states( $countries_states ) {
    $text_domain = "text_domain"; // Set your theme text domain for translations
    
    // Below define your array of state codes and state label names pairs (one state per line)
    $countries_states['AE'] = array(
        'DUB' => __("Dubai", $text_domain),
        'SN2' => __("State name 2", $text_domain),
        'SN3' => __("State name 3", $text_domain),
        'SN4' => __("State name 4", $text_domain),
        'SN5' => __("State name 5", $text_domain),
    );

    return $countries_states;
}

// Define state field For "AE" (United Arab Emirates) as a mandatory dropdown
add_filter( 'woocommerce_get_country_locale', 'custom_uae_country_locale_base', 10, 1 );
function custom_uae_country_locale_base( $locale ) {
    $text_domain = "text_domain"; // Set your theme text domain for translations

    $locale['AE']['state']['required'] = true;
    $locale['AE']['state']['type'] = 'state';
    $locale['AE']['state']['placeholder'] = __("Select a state", $text_domain);

    return $locale;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Then on shipping calculator, you will have:

enter image description here

And also in checkout page (and My account > Edit Addresses section) for United Arab Emirates (AE) selected country…