WooCommerce 在输入 post 代码之前阻止结帐

WooCommerce prevent checkout until post code entered

试图阻止客户在输入邮政编码之前使用 "Proceed to payment" 按钮。但是,我发现使用下面的功能,如果您更改数量并更新购物车 - 该功能不再有效,您可以继续免运费付款。有什么想法吗?

add_action( 'wp_head', 'prevent_proceed_to_checkout' );

function prevent_proceed_to_checkout() {
    echo 'alert(Please enter postcode before payment!")';
}

已更新 - 3 种方式 -(添加了替代方案)

1) 如果没有填写邮政编码,您可以使用以下代码 "avoid proceed to checkout" 结帐:

// 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 文件。已测试并有效。

在购物车页面: