问题
我正在通过对
billing_country
和 shipping_country
下拉字段中的国家/地区重新排序来自定义 WooCommerce 结账页面。我通过使用 woocommerce_checkout_fields
过滤器修改字段选项来实现此目的。
但是,进行这些自定义后,我遇到了一个问题:当
billing_state
字段更改时,billing_country
字段无法正确更新。无论选择哪个国家/地区,州/省选项都保持不变。
当前代码(之前的 Stackoverflow 帖子)
这是我用来对国家/地区重新排序并应用 Select2 (selectWoo) 功能的代码:
// 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();");
}
尝试的解决方案
此代码对下拉列表中的国家/地区重新排序并应用 Select2 (selectWoo) 功能。但是,它没有解决当
billing_state
更改时 billing_country
字段无法正确更新的问题。
我尝试了各种方法,例如向
billing_country
字段添加事件侦听器并相应地更新 billing_state
字段,但我一直无法找到一致工作的解决方案。
问题
即使在自定义国家/地区下拉列表之后,如何确保当
billing_state
字段更改时,billing_country
字段会更新为正确的州/省选项?
显示问题的图像示例
如上图所示,当在 WooCommerce 结帐中选择“奥地利 - 奥地利”作为帐单国家/地区时,州选择字段错误地显示“德国”的州/省,而不是预期的州/省奥地利。
当我注释掉第二行时,问题没有发生
add_filter('woocommerce_checkout_fields', 'reorder_checkout_country_dropdowns');
将所有代码替换为以下内容,以在更改国家/地区时处理国家/地区状态同步:
// Reorder and customize the country dropdowns
add_filter( 'woocommerce_checkout_fields', 'reorder_checkout_country_dropdowns' );
function reorder_checkout_country_dropdowns( $fields ) {
// Merge sorted countries, with unsorted ones
$countries_array = array_merge(
array(
'DE' => 'Germany',
'AT' => 'Austria',
'CH' => 'Switzerland',
'-' => '------------',
),
WC()->countries->get_allowed_countries(),
);
// Change field type from "country" to "select"
$fields['billing']['billing_country']['type'] = $fields['shipping']['shipping_country']['type'] = 'select';
// Set sorted countries options
$fields['billing']['billing_country']['options'] = $fields['shipping']['shipping_country']['options'] = $countries_array;
// Set correct input class for country field
$fields['billing']['billing_country']['input_class'] = $fields['shipping']['shipping_country']['input_class'] = ['country_to_state country_select'];
return $fields;
}
已测试且有效。
不再需要 JavaScript。