The Issue
I'm working on customizing the WooCommerce checkout page by reordering the countries in the billing_country
and shipping_country
dropdown fields. I've achieved this by using the woocommerce_checkout_fields
filter to modify the fields' options.
然而,在进行这些自定义之后,我面临着一个问题,即当更改billing_country
字段时,billing_state
字段不能正确更新.州/省选项保持不变,无论所选国家.
Current Code (Previous Stackoverflow Post)
Here's the code I'm using to reorder the countries and apply the Select2 (selectWoo) functionality:
// Reorder and customize the country dropdowns
add_filter('woocommerce_checkout_fields', 'reorder_checkout_country_dropdowns');
function reorder_checkout_country_dropdowns($fields)
{
$countries_array = array_merge(
array(
'DE' => 'Germany',
'AT' => 'Austria',
'CH' => 'Switzerland',
'-' => '------------',
),
WC()->countries->get_allowed_countries()
);
$fields['billing']['billing_country']['type'] = $fields['shipping']['shipping_country']['type'] = 'select';
$fields['billing']['billing_country']['options'] = $fields['shipping']['shipping_country']['options'] = $countries_array;
return $fields;
}
// Enqueue JavaScript to apply Select2 functionality
add_action('woocommerce_checkout_init', 'enable_back_selectWoo_on_countries_dropdowns');
function enable_back_selectWoo_on_countries_dropdowns()
{
wc_enqueue_js("$('#billing_country,#shipping_country').selectWoo();");
}
Attempted Solutions
This code reorders the countries in the dropdowns and applies the Select2 (selectWoo) functionality. However, it doesn't address the issue with the billing_state
field not updating correctly when the billing_country
is changed.
我try 过各种方法,比如在billing_country
字段中添加一个事件侦听器并相应地更新billing_state
字段,但我还没有找到一个一致工作的解决方案.
The Question
How can I ensure that the billing_state
field updates with the correct state/province options when the billing_country
field is changed, even after customizing the country dropdown?
Image example to show the issue
如上图所示,当WooCommerce checkout 时,"奥地利—奥地利"被选为账单国家时,州 Select 字段错误地显示了"德国"的州/省,而不是奥地利的州/省.
当我注释掉第二行add_filter('woocommerce_checkout_fields', 'reorder_checkout_country_dropdowns');
时,这个问题没有发生.