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 ?