0

I have read various post about redirecting a logged in user if the go to /wp-login.php. However, my case is a little different. I want my users to click a link that takes them to "/wp-login.php?action=register&level=7", for example. If the User is already logged in, then they should be redirected to "membership-account/membership-checkout/?level=7". I have tried the following code.

function custom_level_login_redirect()
{
    $isPageLogin = is_page('login');
    $isUserLoggedIn = is_user_logged_in();
    $level = $_GET['level'];

    if( is_page('login') && is_user_logged_in() && !empty($_GET['level']) && is_numeric($_GET['level'])) {
        $level = intval($_GET['level']);
        $redirect_to = 
            site_url("membership-account/membership-checkout/?level=" . (string) $level, null);    
            wp_redirect( $redirect_to );
            exit();
    }

    return;
}
add_action('login_init', 'custom_level_login_redirect');

The above code does not execute on "login-init". When I tried "wp" as the action then "level" url parameter was not available. The code does not execute if I set it up as filter and use "login_redirect" as the hook. I always get redirected to "?1589985914" which just means the index (home) page.

What action or filter should I hook into to redirect an already logged in user who is sent to the wp-login.php page with url parameters?

1

The code logic above may not evaluate to true, refactor it like so:

function custom_level_login_redirect()
{
    $isPageLogin = is_page('login');
    $isUserLoggedIn = is_user_logged_in();
    $level = (int) $_GET['level'];

    if( $isPageLogin && isUserLoggedin && $level > 0 ) {
        $redirect_to = esc_url_raw( 
            site_url("membership-account/membership-checkout/?level=" . $level, null) );
            exit( wp_redirect( $redirect_to ) );
    }

    return;
}

add_action('login_init', 'custom_level_login_redirect');

Notice the esc_url_raw(), the $level variable casting, and the if() statement.

| improve this answer | |
  • Thank you for cleaning up the code. In my case, the issue ended up being a priority order issue. Another plugin doing a redirect had hooked into the code. The "login_init" action does exist checkout "developer.wordpress.org/reference/hooks/login_init". I think it is not well known. I have read through various descriptions of the login process which have not mentioned this action hook. – ermSO Jun 2 at 12:34
  • login_init hook really does exists. Thank you. – John Zenith Jun 7 at 6:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.