wc_countries – 州选择下拉列表 – woocommerce

我正在努力设置一个默认WooCommerce国家和州选择下拉列表的表单。

基本上,我想显示国家选择,然后根据国家选择显示州选择。 因此,如果用户选择英国,则会显示带有状态选择的新下拉菜单。

我得到了这个:

__get('countries'); $default_country = $countries_obj->get_base_country(); $default_county_states = $countries_obj->get_states( $default_country ); echo '
' . __('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 '
'; echo '
' . __('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 '
'; ?>

国家下降显示了显示商店基础的国家和州的下降 – 英国

但是如何让它们协同工作并保存价值?

找不到任何信息,有没有人有这方面的经验?

首先,有国家和州的类型……你不需要做太多……就像这样……

 echo '
' . __('Countries') . ''; woocommerce_form_field('my_country_field', array( 'type' => 'country', 'class' => array( 'chzn-drop' ), 'label' => __('Item ships from - country'), 'placeholder' => __('Select a Country') ) ); echo '
'; echo '
' . __('States') . ''; woocommerce_form_field('my_state_field', array( 'type' => 'state', 'class' => array( 'chzn-drop' ), 'label' => __('Item ships from - state'), 'placeholder' => __('Select a State') ) ); echo '
';

注意他们的类型…他们不是类型选择。

现在你的问题..

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 + ''; } }