WooCommerce login redirect based on cart

ε祈祈猫儿з 提交于 2019-11-29 16:32:53

To avoid your site to be off, global $woocommerce; is missing.
Now global $woocommerce; with $woocommerce->cart is now simply replaced by WC()->cart.

To check if cart is empty, you should use WC()->cart->is_empty(), as is_empty() is a conditional method of WC_cart class.

After, on checkout page (in both cases) if user is not logged in, you want to redirect him to my_account page (login/create account area).

Now on my_account page, when a logged user has something in his cart, you want to redirect him on checkout page.

Here is the code you need:

add_action('template_redirect', 'woocommerce_custom_redirections');
function woocommerce_custom_redirections() {
    // Case1: Non logged user on checkout page (cart empty or not empty)
    if ( !is_user_logged_in() && is_checkout() )
        wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );

    // Case2: Logged user on my account page with something in cart
    if( is_user_logged_in() && ! WC()->cart->is_empty() && is_account_page() )
        wp_redirect( get_permalink( get_option('woocommerce_checkout_page_id') ) );
}

Code goes in function.php file of your active child theme. Tested and works.


Reference (Woocommerce documentation):

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!