我正在努力设置一个带有默认 WooCommerce 国家和州选择下拉列表的表单。
基本上,我想显示国家选择,然后根据国家选择显示状态选择。因此,如果用户选择英国,将显示带有州选择的新下拉菜单。
我做到了这一点:
<?php
global $woocommerce;
$countries_obj = new WC_Countries();
$countries = $countries_obj->__get('countries');
$default_country = $countries_obj->get_base_country();
$default_county_states = $countries_obj->get_states( $default_country );
echo '<div id="ships_from_countries_field">' . __('Countries') . '';
woocommerce_form_field('my_country_field', array(
'type' => 'select',
'class' => array( 'chzn-drop' ),
'label' => __('Item ships from - country'),
'placeholder' => __('Select a Country'),
'options' => $countries
)
);
echo '</div>';
echo '<div id="ships_from_state_field">' . __('States') . '';
woocommerce_form_field('my_state_field', array(
'type' => 'select',
'class' => array( 'chzn-drop' ),
'label' => __('Item ships from - state'),
'placeholder' => __('Select a State'),
'options' => $default_county_states
)
);
echo '</div>';
?>
国家下拉列表显示国家和州下拉列表显示商店基地的状态 - 英国
但我如何让它们协同工作并保存值呢?
找不到任何信息,有人有任何使这项工作成功的经验吗?
最佳答案
首先,有一个国家和州的类型..你不需要做太多......就像这样......
echo '<div id="ships_from_countries_field">' . __('Countries') . '';
woocommerce_form_field('my_country_field', array(
'type' => 'country',
'class' => array( 'chzn-drop' ),
'label' => __('Item ships from - country'),
'placeholder' => __('Select a Country')
)
);
echo '</div>';
echo '<div id="ships_from_state_field">' . __('States') . '';
woocommerce_form_field('my_state_field', array(
'type' => 'state',
'class' => array( 'chzn-drop' ),
'label' => __('Item ships from - state'),
'placeholder' => __('Select a State')
)
);
echo '</div>';
注意它们的类型...它们不是 select 类型。
现在解决你的问题..
PHP
你需要有针对国家和州的本地化脚本...我不会继续如何使用 wp_localize_script()
.如果需要,请阅读链接。这是它的一部分。
$wc_country = array(
'country' => json_encode( array_merge( WC()->countries->get_allowed_country_states(), WC()->countries->get_shipping_country_states() ) )
);
wp_localize_script( 'my-js', 'my_js', $wc_country );
javascript
这样,在您的 my-js
脚本(脚本文件)中,您可以像这样读取状态:
var states_json = my_js.countries.replace( /"/g, '"' ),
states = $.parseJSON( states_json );
然后您必须在您的国家/地区添加更改事件并根据选择的国家/地区重新填充状态...
示例:states["PH"]
如果选择的国家/地区是菲律宾
00: "Metro Manila"
ABR: "Abra"
AGN: "Agusan del Norte"
AGS: "Agusan del Sur"
AKL: "Aklan"
ALB: "Albay"
ANT: "Antique"
APA: "Apayao"
AUR: "Aurora"
BAN: "Bataan"
BAS: "Basilan"
BEN: "Benguet"
BIL: "Biliran"
.....
WSA: "Samar"
ZAN: "Zamboanga del Norte"
ZAS: "Zamboanga del Sur"
ZMB: "Zambales"
ZSI: "Zamboanga Sibugay"
然后您可以像这样使用 jQuery 构建您的选项..
var options = '',
state = states[ country ]; // country can be: var country = $('country').val();
for( var index in state ) {
if ( state.hasOwnProperty( index ) ) {
options = options + '<option value="' + index + '">' + state[ index ] + '</option>';
}
}
关于javascript - wc_countries - 状态选择下拉列表 - woocommerce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34757408/