skip to Main Content

I have a specific site on my website which needs to be logged in.
So if I visit the page and I am not logged in, I want to redirected to wp-loginand back to the page. But everything I am trying, I will always redirected to wp-admin

That is one of my failures:

add_action( 'template_redirect', [ $this, 'redirect_to_login_page' ] );
public function redirect_to_login_page() {
        if ( ! is_user_logged_in() && strpos( $_SERVER['REQUEST_URI'], '/test' ) !== false ) {
            $login_url = add_query_arg( 'redirect_to', site_url( '/test' ), wp_login_url() );
            wp_redirect( $login_url );
            exit;
        }
    }

What can I do?

2

Answers


  1. you can use the itheme security plugin its not going to redirect
    enter image description here

    Login or Signup to reply.
  2. To generate the login URL with the desired redirect URL already included. Then, we’re using wp_redirect() to redirect the user to the login page.

    Try below code

    add_action( 'template_redirect', [ $this, 'redirect_to_login_page' ] );
    
    public function redirect_to_login_page() {
        if ( ! is_user_logged_in() && strpos( $_SERVER['REQUEST_URI'], '/test' ) !== false ) {
            $login_url = wp_login_url( site_url( '/test' ) );
            wp_redirect( $login_url );
            exit;
        }
    }
    

    If the issue still not fixed and you’re being redirected to the wp-admin page instead of the login page, you might want to check your WordPress settings to make sure that the login URL is set correctly.

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