已更新 - 3 种方式 - (添加了替代方法)
1) 如果邮政编码未填写,您可以使用以下代码“避免继续结帐”结帐:
// Avoiding checkout when postcode has not been entered
add_action( 'woocommerce_check_cart_items', 'check_shipping_postcode' ); // Cart and Checkout
function check_shipping_postcode() {
$customer = WC()->session->get('customer');
if( ! $customer['calculated_shipping'] || empty( $customer['shipping_postcode'] ) ){
// Display an error message
wc_add_notice( __("Please enter your postcode before checkout", "woocommerce"), 'error' );
}
}
代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。
购物车页面:
结帐页面中:
2) 尝试这种替代方式(检查邮政编码并重定向到购物车以避免结帐):
add_action('template_redirect', 'check_shipping_postcode');
function check_shipping_postcode() {
// Only on checkout page (and cart for the displayed message)
if ( ( is_checkout() && ! is_wc_endpoint_url() ) || is_cart() ) {
$customer = WC()->session->get('customer');
if( ! $customer['calculated_shipping'] || empty( $customer['shipping_postcode'] ) ){
wc_add_notice( __("Please enter your postcode before checkout", "woocommerce"), 'error' );
if( ! is_cart() ){
wp_redirect(wc_get_cart_url());
exit();
}
}
}
}
代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。
购物车页面:
3)以上两者的组合(避免结帐页面):
// Avoiding checkout when postcode has not been entered
add_action( 'woocommerce_check_cart_items', 'check_shipping_postcode' ); // Cart and Checkout
function check_shipping_postcode() {
$customer = WC()->session->get('customer');
if( ! $customer['calculated_shipping'] || empty( $customer['shipping_postcode'] ) ){
// Display an error message
wc_add_notice( __("Please enter your postcode before checkout", "woocommerce"), 'error' );
}
}
add_action('template_redirect', 'shipping_postcode_redirection');
function shipping_postcode_redirection() {
// Only on checkout page
if ( is_checkout() && ! is_wc_endpoint_url() ) {
$customer = WC()->session->get('customer');
if( ! $customer['calculated_shipping'] || empty( $customer['shipping_postcode'] ) ){
wp_redirect(wc_get_cart_url());
exit();
}
}
}
代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。
购物车页面: