【发布时间】:2018-09-29 06:48:17
【问题描述】:
我需要将 woocommerce 运输状态限制为一个(印度的一个州),而不更改帐单地址中的状态。我曾尝试使用 woocommerce_states 挂钩,但这将替换送货地址和帐单地址中的状态。
过去一周我一直在寻找解决方案,但找不到正确的解决方案。
【问题讨论】:
标签: php wordpress woocommerce state hook-woocommerce
我需要将 woocommerce 运输状态限制为一个(印度的一个州),而不更改帐单地址中的状态。我曾尝试使用 woocommerce_states 挂钩,但这将替换送货地址和帐单地址中的状态。
过去一周我一直在寻找解决方案,但找不到正确的解决方案。
【问题讨论】:
标签: php wordpress woocommerce state hook-woocommerce
代码更新:
首先,您需要为您的商店进行一些设置(选择的商店状态将是发货状态),并且唯一可用的发货国家/地区将是印度:
以下代码会将商店位置状态设置为唯一可用的发货状态,并将在“结帐”和“我的帐户”>“编辑地址”页面中将下拉菜单设为只读(非活动):
add_filter('woocommerce_shipping_fields', 'shipping_state_preselected_read_only', 900, 1 );
function shipping_state_preselected_read_only($fields) {
// Get shop location country and state
$shop_country_code = WC()->countries->get_base_country();
$shop_state_code = WC()->countries->get_base_state();
$shop_state_name = WC()->countries->get_allowed_country_states()[$shop_country_code][$shop_state_code];
// Set customer shipping country and state to shop location
WC()->customer->set_shipping_country($shop_country_code);
WC()->customer->set_shipping_state($shop_state_code);
// Set shipping country field to shop location
$fields['shipping_state']['option'] = array( $shop_state_code => $shop_state_name );
$fields['shipping_state']['default'] = $shop_state_code;
$fields['shipping_state']['value'] = $shop_state_code;
// Make the field read only
$fields['shipping_state']['custom_attributes'] = array('disabled' => 'disabled');
return $fields;
}
代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。
结帐时只有一个发货状态只读和我的帐户编辑地址(基于商店的状态):
由于预先选择了印度作为唯一的发货国家/地区,因此该国家/地区不会出现任何验证问题。
【讨论】:
首先在woo commerce发货设置页面设置发货地点。我设置了“印度”
然后将以下代码粘贴到您的活动主题functions.php 文件中。 我已将仅送货状态设置为仅“泰米尔纳德邦”。
add_action('wp_footer', 'checkout_shipping_states');
function checkout_shipping_states() {
if(!is_checkout()) {
return;
}
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$(document.body).on('country_to_state_changed', function(event, args) {
function set_shipping_states(states) {
var $shipping_state = $('#shipping_state');
$shipping_state.find('option:not([value=""])').remove();
for(state in states) {
$shipping_state.append('<option id="' + state + ' value="' + state + '">' + states[state] + '</option>');
}
}
var $shipping_country = $('#shipping_country');
var new_shipping_states = {};
switch($shipping_country.val()) {
case 'IN':
new_shipping_states = {
'TN': 'Tamil Nadu'
}
break;
}
if(!$.isEmptyObject(new_shipping_states)) {
set_shipping_states(new_shipping_states);
}
});
});
</script>
<?php
};
在屏幕下方查看
【讨论】: