Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 ?

share|improve this question
    
did you manage to solve this? This is happening to me too.. I am getting stuck on the login page. Thanks! –  enriqg9 Jul 30 '13 at 22:28
    
@enriqg9 : See my answer below and tell me if it solves your problem. –  Fabien Quatravaux Jul 30 '13 at 23:31

2 Answers 2

up vote 1 down vote accepted

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:

add_filter( 'auth_redirect_scheme', 'wpse16975_check_loggedin' );
function wpse16975_check_loggedin(){
    return 'logged_in';
}

Then auth_redirect() will work as expected : redirect users to the login form if they are not logged in.

share|improve this answer
    
Cool! This fixed it for me too - weird it worked fine on another site without this fixed... thanks a lot! –  andrux Aug 19 at 0:35

See in the end of this

if (! is_user_logged_in())
    auth_redirect();
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.