WooCommerce 中允许非结账访客的重定向

Redirection for non checkout guest allowed in WooCommerce

回答我之前的问题后,以下代码将用户重定向到登录页面:

add_action( 'template_redirect', 'checkout_redirect_non_logged_to_login_access');
function checkout_redirect_non_logged_to_login_access() {
    if( is_checkout() && !is_user_logged_in()){
        wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );
        exit;
    }
} 

但我有一些产品允许客人结账(请参阅上面的链接 question/answer)。那么我该如何修复允许访客结帐的产品代码以禁用该代码重定向?

您可以将我之前的答案代码替换为以下内容:

// Custom conditional function that checks if checkout registration is required
function is_checkout_registration_required() {
    if ( ! WC()->cart->is_empty() ) {
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $item ) {
            // Check if there is any item in cart that has not the option "Guest checkout allowed"
            if ( get_post_meta( $item['product_id'], '_allow_guest_checkout', true ) !== 'yes' ) {
                return true; // Found: Force checkout user registration and exit
            }
        }
    }
    return false;
}

add_filter( 'woocommerce_checkout_registration_required', 'change_tax_class_user_role', 900 );
function change_tax_class_user_role( $registration_required ) {
    return is_checkout_registration_required();
}

那么您当前的问题代码将改为:

add_action( 'template_redirect', 'checkout_redirect_non_logged_to_login_access');
function checkout_redirect_non_logged_to_login_access() {
    if( is_checkout() && !is_user_logged_in() && is_checkout_registration_required() ){
        wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );
        exit;
    }
} 

代码进入您的活动子主题(或活动主题)的 functions.php 文件。它应该有效。