0

I want to login a user before he watches content of our site but I am always in a redirect loop, I don't know why. but I searched all the google and stackoverflow but could not find it's solution. Please take a look at my codes

function redirect_login_page() {
    if ( ! is_user_logged_in() ) {
        wp_redirect( home_url('/account/') );
        exit;
    }
}
add_action( 'template_redirect', 'redirect_login_page' );

I also tried this

function redirect_login_page() {
    if ( ! is_user_logged_in() ) {
        wp_redirect( 'https://playground.com/account/' );
        exit;
    }
}
add_action( 'template_redirect', 'redirect_login_page' );

Nothing of the upper works perfect.I always get this ....redirected you too many times.

But as per wp_redirect there might be any problem. I also used this wp_redirect( home_url('/account/'), 302 ); / wp_redirect( home_url('/account/'), 301 ); etc etc

1

You are establishing a redirect for all requests for a visitor, including /account:

  • Request to /, user is not logged in - redirect to /account.
  • Request to /account, user is not logged in - redirect to /account.
  • Request to /account, user is not logged in - redirect to /account.
  • (etc.)

To break the loop, perform the redirect only if the request is not for your login page:

function redirect_login_page() {
    if ( ! is_user_logged_in() && ! is_page( 'account' ) ) {
        wp_redirect( home_url('/account/') );
        exit;
    }
}
add_action( 'template_redirect', 'redirect_login_page' );

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.