skip to Main Content

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.
I have added below code in my active theme’s function.php file but still having same problem

add_action( 'template_redirect', 'check_if_logged_in' );
function check_if_logged_in() {
    $pageid = 817; // 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;
    }
}

What I am doing wrong? Thanks in advance everyone.

2

Answers


  1. Try this code:

    add_action( 'template_redirect', 'template_redirect_action' );
    function template_redirect_action() {
        if ( is_checkout() && ! is_user_logged_in() ) {
            $url = add_query_arg(
                'redirect_to',
                wc_get_checkout_url(),
                get_permalink( get_option( 'woocommerce_myaccount_page_id' ) )
            );
    
            wp_safe_redirect( $url );
            exit;
        }
    }
    

    Tested and works.

    Login or Signup to reply.
  2. Simply use a redirect to my-admin when user is not logged in as follows:

    add_action( 'template_redirect', 'unlogged_user_checkout_redirect' );
    function unlogged_user_checkout_redirect() {
        if ( is_checkout() && ! is_user_logged_in() ) {
            wp_safe_redirect( get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) );
            exit();
        }
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search