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();
}
});
I know I am late for the party. I heard Big and Pac were rocking hard…
Anyways, this is what I usually do:
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.
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…
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.
Let’s say the user is not logged in.
Then your code thinks in this way:
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: