Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce check and redirect to login before checkout

The default Woocommerce checkout behavior breaks a lot of web conventions by showing the "Create Account" boxes on the checkout page if it detects the user is not logged in. New users may not know what to do without any added instructions.

My desired sequence would be:

User Checkout > Check login >

  • Proceed to checkout if logged in.
  • Redirect to login/register page if not logged in > proceed to the checkout page.

This is EXACTLY the case in WooCommerce login redirect based on cart

However, what I feel uncomfortable is that, in the above case, once the user logged in, he/she will be redirected to the checkout page if the cart is not empty. If the user's cart is not empty, he/she will not be able to go to MyAccount at all even though he/she does not want to checkout yet.

Any idea on this one?

like image 258
user9276838 Avatar asked Nov 25 '25 00:11

user9276838


1 Answers

In the second answer there is a problem, after loging in the user always redirects checkout page, it does not stand on my-account page until the cart become empty!!


This code redirects the user to my-account page for login instead of checkout if the user is not logged in, then after loging in it automatically redirects to checkout page.
STEP 1:
Add this code in function.php

add_action('template_redirect','check_if_logged_in');
function check_if_logged_in()
{
    $pageid = get_option( 'woocommerce_checkout_page_id' );// your checkout page id
    if(!is_user_logged_in() && is_page($pageid))
    {
        $url = add_query_arg(
            'redirect_to',
            get_permalink($pageid),
            site_url('/my-account/') // your my acount url
        );
        wp_redirect($url);
        exit;
    }
}

STEP 2:
Add this code at the end of /wp-content/plugins/woocommerce/templates/myaccount/my-account.php

<?php
$quark_web_solution_redirect = $_GET['redirect_to'];
if (isset($quark_web_solution_redirect)) {
echo '<script>
window.location.href = "'.$quark_web_solution_redirect.'";
</script>';
}
?>
like image 144
Sudipta Modak Avatar answered Nov 28 '25 15:11

Sudipta Modak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!