Skip to content
Advertisement

Check and redirect to log in before checkout redirecting on wrong URL

I am using woocommerce and I have created a login and register page. I am not using any plugin for this.

My issue is, I have to check and redirect to log in before checkout I refer to this code(WooCommerce check and redirect to login before checkout)

I am using the below code

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

but when I click Proceed to checkout then I am getting the URL like

http://examle.com/my-account/?redirect_to=http://example.com/index.php/checkout/

Advertisement

Answer

You could do it in two steps.

If the user goes to checkout and is not logged in, he is redirected to the my-account page for login or registration.

// 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;
    }
}

After login or registration, if the cart is not empty, the user is redirected to checkout.

// redirect to checkout after login (or registration)
add_filter( 'woocommerce_registration_redirect', 'redirect_after_login_or_registration_to_checkout_page' );
add_filter( 'woocommerce_login_redirect', 'redirect_after_login_or_registration_to_checkout_page' );
function redirect_after_login_or_registration_to_checkout_page() {
    // only if the cart is not empty
    if ( ! WC()->cart->is_empty() ) {
        return wc_get_page_permalink( 'checkout' );
    } else {
        return home_url();
    }
}

The code has been tested and works. Add it to your theme’s functions.php.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement