WooCommerce basket-based login redirects

I want to apply the following 2 cases:

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 is:

 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');

The above code works fine for my first case. But for my second case, when I look through the cart with , my site stops working. if ( sizeof( $woocommerce->cart->cart_contents ) == 0 ) {}

I put this in the functions.php theme.

What am I doing wrong?

thank

+2
source share
1 answer

First, to make sure that the trash is empty , you should use the WC_cart class as a conditional method . WC()->cart->is_empty() is_empty()

, checkout ( ), , my_account ( / ).

my_account, - , .

, :

function woocommerce_custom_redirects() {

    // 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') ) );
}
add_action('template_redirect', 'woocommerce_custom_redirects');

, function.php ( ), .

.


:

+8

Source: https://habr.com/ru/post/1655954/


All Articles