Redirect to specific page if not logged in WordPress
15,034
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.
Author by
Benjamin Cuslidge
Updated on June 05, 2022Comments
-
Benjamin Cuslidge almost 2 years
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(); } });
-
Sorin C over 8 yearsCheck if
is_page('login-to-view')
gives the expected result. Comment out theif
block, and do something likeif ( is_page('login-to-view') ){echo '<script>alert("This is the page!")</script>';}
. Go visit some pages and see if this is working as it should. Especially on your 'login-to-view' page