This blog help us to achieve a condition where WooCommerce check and redirect customer to login page before checkout and once login done redirect back to checkout page if there is something in cart.
WooCommerce has defined pages that directs customer from shop page to checkout page. It’s easy to implement for shop owners and provides huge customizations via plugins or hook codes. Recently one of our client ask “If we can direct customer to login page from checkout page if he/she not logged in?” and “redirect back to checkout page once login done?”
Well this seems bit tricky but we used a simple trick to achieve the same. So here is our logic
- On checkout page (in both cases) if user is not logged in, we will redirect him to my_account page (login/create account area).
- Once Login done, we will redirect him again to checkout page.
Also if customer has something in cart, he/she will be redirect back to checkout page. So to get this done, copy the below code and add it to functions.php file of child theme.
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') ) );
}
Above code tested and worked with WC Version 6.5.1
So try the code and let us know if it works. Happy Coding!
[caldera_form id=”CF60ca2e3ccf64f”]