I am trying to use auth_redirect
to automatically redirected not logged-in visitors when then visit a specific page.
Here is the code I use:
add_action('template_redirect','wpse16975_check_if_logged_in');
function wpse16975_check_if_logged_in(){
$pageid = 29;
if(is_page($pageid)) auth_redirect();
}
The redirection works (I see the login page), but when I log in, I see the login page again. There is no way to access to the protected page because the browser keeps redirecting it to the login page.
I saw this question and its answer from @chrisguitarguy and modify my code to this :
add_action('template_redirect','wpse16975_check_if_logged_in');
function wpse16975_check_if_logged_in(){
$pageid = 29;
if(!is_user_logged_in() && is_page($pageid)) {
$url = add_query_arg(
'redirect_to',
get_permalink($pageid),
site_url('wp-login.php')
);
wp_redirect($url);
exit;
}
This code solved my problem : a logged in user can now access to the page. The question is : why cannot simply use auth_redirect
?
The problem is that this function is normally used in the backend. To use it in the frontend, you need to add the following filter:
Then
auth_redirect()
will work as expected : redirect users to the login form if they are not logged in.See in the end of this
The problem was, you put yourself into a loop. Your original code block, said that if I visit this page, send me to the login page. After logging in, then it went back to the page, which since you are now visiting the page, go to the login page. Round and round you go!
The new block first checks to see if you are logged in or not. If not, then and only then does it look to see what page you are visiting. If you are not logged in, then you get sent there and after logging in sent back. Now, since you are logged in, you get to see the page.
Make sense?
Been having problems with auth_redirect() only on mobile.
After four days – I wrote a solution that works, and doesn’t need auth_redirect.