[英]Make Billing Phone required on Checkout Field Based on Shipping Method - Woocommerce
I want to set the billing phone number required or not required based on the shipping method.我想根据送货方式设置需要或不需要的账单电话号码。
I have set the shipping method as an array and checked it from the session selected shipping method but it not working我已将送货方式设置为数组,并从 session 选择的送货方式中进行了检查,但它不起作用
add_filter('woocommerce_checkout_fields', 'fire_remove_billing_checkout_fields');
function fire_remove_billing_checkout_fields($fields) {
global $woocommerce;
$methods = array('flat_rate:2', 'flat_rate:3', 'flat_rate:17', 'flat_rate:20');// Set shipping method to hide the checkout field(s).
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if(in_array($chosen_shipping, $methods)){
$fields['billing']['billing_phone'][ 'required' ] = true;
}else{
$fields['billing']['billing_phone'][ 'required' ] = false;
}
return $fields;
}
Your code works well for me.您的代码对我来说效果很好。 I've added my shipping rate IDs and it works as expected, however refresh of the page is necessary , because WooCommerce doesn't refresh the billing fields natively on
update_checkout
trigger.我已经添加了我的运费 ID,它按预期工作,但是需要刷新页面,因为 WooCommerce 不会在
update_checkout
触发器上本地刷新账单字段。
You should either reload the page using Javascript/jQuery on updated_checkout
event, or reload only the billing fields using AJAX like so:您应该在
updated_checkout
事件上使用 Javascript/jQuery 重新加载页面,或者使用 AJAX 仅重新加载账单字段,如下所示:
add_action( 'wp_footer', 'reload_billing_fields_on_updated_checkout' );
function reload_billing_fields_on_updated_checkout() {
?>
<script>
jQuery(document.body).on('updated_checkout', () => {
jQuery('.woocommerce-billing-fields').load(`${location.href} .woocommerce-billing-fields>*`, '');
});
</script>
<?php
}
Keep in mind that it might take a short while for those fields to reload, so you might want to add some loading CSS classes, or maybe a spinner.请记住,重新加载这些字段可能需要一段时间,因此您可能需要添加一些加载 CSS 类,或者添加一个微调器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.