I want to apply following 2 case :
- If User not logged in and cart is empty: Then redirect user to login and then my account
- If User not logged in and cart has product: Then redirect user to login and after login redirect to checkout
My Code :
function wpse_Nologin_redirect() {
if (
! is_user_logged_in()
&& (is_checkout())
) {
// feel free to customize the following line to suit your needs
$MyLoginURL = "http://example.in/my-account/";
wp_redirect($MyLoginURL);
exit;
}
}
add_action('template_redirect', 'wpse_Nologin_redirect');
Above code is working fine for my first case. But for my second case, when I check cart with if ( sizeof( $woocommerce->cart->cart_contents ) == 0 ) {}
, my site stops working.
I have added this code in my theme's functions.php file.
What I am doing wrong?
Here is the code you need:
Code goes in function.php file of your active child theme. Tested and works.
Reference (Woocommerce documentation):
WC_Cart
—is_empty()
method