Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable checkout page for not logged in users

In WooCommerce, I'm trying to find a way to disable the woocommerce checkout page for non logged users, OR when they try to checkout they get redirected to the log in page.

So they should log in first to be able to continue their checkout.

Is that possible?

Thanks

like image 653
Hazem Motahar Avatar asked Mar 10 '23 18:03

Hazem Motahar


1 Answers

Is possible to redirect non logged customers that trying to access to checkout with this code:

add_action( 'template_redirect', 'checkout_redirect_non_logged_to_login_access');
function checkout_redirect_non_logged_to_login_access() {

    // Here the conditions (woocommerce checkout page and unlogged user)
    if( is_checkout() && !is_user_logged_in()){

        // Redirecting to your custom login area
        wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );

        // always use exit after wp_redirect() function.
        exit;
    }
}

Then you can display a custom notice in cart page with a button linked to login area, to avoid customer frustration. Is better to warn customer before, than after.

// Displaying a message on cart page for non logged users (Optional)
add_action( 'woocommerce_before_cart', 'customer_redirected_displaying_message');
function customer_redirected_displaying_message() {
    if( !is_user_logged_in() ){
        // HERE Type your displayed message and text button
        $message = __('To access checkout, you need first to be logged in', 'woocommerce');
        $button_text = __('Login area', 'woocommerce');

        $cart_link = get_permalink( get_option('woocommerce_myaccount_page_id') );

        wc_add_notice(  $message . '<a href="' . $cart_link . '" class="button wc-forward">' . $button_text . '</a>', 'notice' );
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

The code is tested and works.

like image 116
LoicTheAztec Avatar answered Mar 19 '23 08:03

LoicTheAztec