以下代码有效,显示要运送货件的国家/地区:
add_action( 'woocommerce_before_checkout_form', 'message', 10 );
function message(){
$zone = WC()->session->get('customer')['shipping_country'];
if( $zone == "SK" ) //
{
echo "$zone";
} else {
echo "Other zone";
}
}
但是,如果客户更改地址,woocommerce_before_checkout_form 中的文本将不会更新,即刷新将不起作用。
我尝试了其他挂钩,但没有成功。
如何解决这个问题?以某种方式通过ajax 进行调用?
任何帮助将不胜感激。
这可以通过对代码和一些 jQuery 代码进行一些更改来完成,如下所示:
add_action( 'woocommerce_before_checkout_form', 'checkout_delivery_zone_message', 10 );
function checkout_delivery_zone_message(){
$zone = WC()->session->get('customer')['shipping_country'];
$countries = WC()->countries->get_countries();
$shop_zone = 'SK';
$is_shop_zone = $zone === $shop_zone;
$display_none = ' style="display:none;"';
printf('<div class="message-zone"><span class="sk"%s>%s</span><span class="other"%s>%s</span></div>',
$is_shop_zone ? '' : $display_none,
$countries[$shop_zone] . __(" zone", "woocommerce"),
$is_shop_zone ? $display_none : '',
__("Other zone", "woocommerce") );
}
add_action( 'wp_footer', 'checkout_delivery_zone_message_js', 10 );
function checkout_delivery_zone_message_js() {
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script>
jQuery(function($){
$('form.checkout').on('change', '[name=billing_country],[name=shipping_country]', function(){
var countryCode = null;
if( ( ! $('[name=ship_to_different_address]').prop('checked') && $(this).prop('id') === 'billing_country' ) ||
( $('[name=ship_to_different_address]').prop('checked') && $(this).prop('id') === 'shipping_country' ) ) {
countryCode = $(this).find('option').filter(':selected').val();
}
if ( countryCode !== null ) {
if ( countryCode === 'SK' ) {
$('.message-zone .sk').show();
$('.message-zone .other').hide();
} else {
$('.message-zone .other').show();
$('.message-zone .sk').hide();
}
}
}).on('change', '[name=ship_to_different_address]', function(){
var countryCode = null;
if( $(this).prop('checked') ) {
countryCode = $('[name=shipping_country] option').filter(':selected').val();
} else {
countryCode = $('[name=billing_country] option').filter(':selected').val();
}
if ( countryCode !== null ) {
if ( countryCode === 'SK' ) {
$('.message-zone .sk').show();
$('.message-zone .other').hide();
} else {
$('.message-zone .other').show();
$('.message-zone .sk').hide();
}
}
});
});
</script>
<?php
endif;
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。