WooCommerce 购物车运费计算器仅限于特定州

时间:2021-02-07 06:58:32

标签: php wordpress woocommerce cart shipping

我正在使用 woocommerce。在购物车页面上有一个运费计算器。我想在州/国家下拉字段中设置我自己的州。我希望它在有人进入购物车页面时自动预设。 Check this pic

我找到了这个钩子,我认为它可以在这里使用,但我不知道如何使用它

function custom_woocommerce_calculated_shipping(){ 
    // Do something here
} 

add_action('woocommerce_calculated_shipping', 'custom_woocommerce_calculated_shipping');

1 个答案:

答案 0 :(得分:1)

钩子 woocommerce_calculated_shipping 不能用于定义(限制到)特定国家/地区的特定状态。

由于 WooCommerce 中未定义阿拉伯联合酋长国 (AE) 的州,您需要:

  1. 将“AE”国家的州字段设置为必填下拉字段,
  2. 在州代码和州标签名称对的数组中为“AE”国家定义所有州(注意州代码需要大写西方字符)

代码:

// 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;
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。

然后在运费计算器上,您将获得:

enter image description here

还有在阿拉伯联合酋长国(AE)选定国家/地区的结帐页面(和我的帐户>编辑地址部分)......