Andres Molina Perez-Tome Andres Molina Perez-Tome - 2 months ago 13
PHP Question

Non logged in users Woocommerce, redirection

I'm doing a shop online with Woocommerce, where my client ask me he don't want people to be able to register, he will create a user and password for each one of his clients. That way he can control who buys on his shop.

So i went into Woocommerce and disable the registration at checkout and everywhere, and the option to allow guests to place orders. Everything works fine, except that when someone tries to place an order, when logged out, when he tries to go to the checkout page, it just shows an unformatted message saying "You must be logged in to place an order" which is not nice. Is there a way where I can redirect not logged in customers to login page, when trying to access checkout?

Thanks so much in advance
Kind regards

Answer

Use the following code in functions.php

add_action( 'template_redirect', 'redirect_user_to_login_page' );

function redirect_user_to_login_page(){
    // Make sure your checkout page slug is correct
    if( is_page('checkout') ) {
        if( !is_user_logged_in() ) {
            // Make sure your login page slug is correct in below line
            wp_redirect('/my-account/');
        }
    }
}
Comments