loop issues in login page for (back button) when I use a function for (login before checkout)

I use WordPress and WooCommerce and a digits (login signup) plugin
I found a function in Stackoverflow in the below link:
Check and redirect to log in before checkout redirecting on wrong URL
and use this part and works well.

//If the user is not logged in, return him to login before checkout
add_action('template_redirect', 'check_if_logged_in');
function check_if_logged_in() {
    if ( ! is_user_logged_in() && is_checkout() ) {
        $url = site_url('/my-account/');
        wp_redirect( $url );
        exit;
    }
}

but I have a problem with the back button on the login page!
On the login page, the back button gets url from the before page. which is clear here is the checkout page.
This function works correctly. It causes when the user (not logged in) wants to enter the payment page, he will be transferred to the login page first. And then there when he logs in. You will be redirected to the payment page. And then he can complete his purchase.

Please see this image from my login page and custom until I changed function

My only problem is with the back button on the login/registration page. (If) the user does not enter there and clicks on the back or exit button, and because it is referred to the payment page again and because there is a condition on the payment page that if the user does not enter, it will redirect to the login page. will be So we have a loop here.

In fair conditions, we have no problem with this function and everything works fine.
The problem exists only when the user does not log in on the login page and hits the back button. That’s when he can never leave the login page! Unless it closes the browser or tab!

Here I put the function I used

add_action('template_redirect', 'check_if_logged_in');
function check_if_logged_in() {
    if ( ! is_user_logged_in() && is_checkout() ) {
        $url = site_url('/checkout/?login=true&page=1&redirect_to=https://mysitedomain.ir/checkout/');
        wp_redirect( $url );
        exit;
    }
}

Leave a Comment