Redirect to specific page if not logged in WordPress

I am trying to have it on my WordPress site to redirect to a landing page if the user is not logged in, but it always gets stuck in a redirect loop. This is basically what I have (in functions.php)…

    add_action( 'template_redirect', function() {

        if ( !is_user_logged_in() && ! is_page('login-to-view') ){
            wp_redirect( site_url( '/login-to-view' ) );
            exit();
        }

     });

Related posts

3 comments

  1. I know I am late for the party. I heard Big and Pac were rocking hard…
    Anyways, this is what I usually do:

    1. Create a login page, e.g. http://www.site.com/login
    2. In my functions.php I add the following code:
    add_action( 'template_redirect', function() {
    
        if( ( !is_page('login') ) ) {
    
            if (!is_user_logged_in() ) {
                wp_redirect( site_url( '/login' ) );        // redirect all...
                exit();
            }
    
        }
    
    });
    

    Explanation:
    What happens above is access to every page on the site is restricted except for the login page. You can choose to exclude or include additional pages if you want and also the wp-admin URLs as well.

  2. The issue is that I had the function in functions.php. is_page didn’t know what page it is on yet. I moved it to the header, just before the doctype declaration and it works now with just this…

    if ( ! is_page('login-to-view')  &&  ! is_user_logged_in() ){
        wp_redirect( site_url( '/login-to-view' ) );
        exit();
    }
    

    Another thing to note… I wasn’t able to get it to work on my localhost, I’m thinking because site_url can’t be found, and it was just redirecting to localhost:8888/login-to-view

    I’m using MAMP, but I’m guessing you can set up URL paths like that in the PRO version.

  3. Let’s say the user is not logged in.

    Then your code thinks in this way:

    1. Is user logged in?
    2. NO? Then do wp_redirect.

    The user gets redirected to your page, and the process begins again. That’s why you get the infinite loop.

    Try altering the order of checks instead:

    <?php 
    
        add_action( 'template_redirect', function() {
    
        if ( ! is_page('login-to-view')  &&  ! is_user_logged_in() ){
            wp_redirect( site_url( '/login-to-view' ) );
            exit();
        }
    
     });
    

Comments are closed.