WooCommerce中允许非结帐访客重定向 [英] Redirection for non checkout guest allowed in WooCommerce

查看:46
本文介绍了WooCommerce中允许非结帐访客重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

允许访客结帐特定产品之后仅在WooCommerce中回答了我的上一个问题,以下代码将用户重定向到登录页面:

After Allow guest checkout for specific products only in WooCommerce answer to my previous question, the following code redirect users to login page:

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;
    }
} 

但是我有一些产品允许客人结帐(请参阅上面的链接的问题/答案).那么,如何为允许访客结帐的代码修复产品代码?

But I have some products which allows guest checkout (see the linked question/answer above). So how could I fix my code for the products which allows guest checkout to disable that code redirection?

推荐答案

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

You can replace my previous answer code with the following:

// 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();
}

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

Then your current question code will be instead:

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文件中.应该可以.

Code goes in functions.php file of your active child theme (or active theme). It should works.

这篇关于WooCommerce中允许非结帐访客重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆