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.

Surprised I haven't found this Q.

I want to force users to login to the site before accessing any of the content.

I have this function:

function av_force_user_login() {
    global $post;
    global $pagenow;
    if ( in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ) ) {
        return;
    }else{
        auth_redirect();
    }
}
add_action( 'get_header', 'av_force_user_login' );

This doesn't seem to work though and after I try and login I get redirected back to the login page.

One caveats to watch out for (in my case): I'm using BuddyPress' registration system which doesn't apply to the login page but it would apply to the wp-login.php?action=register page which redirects to Buddypress' template for registration.

Nevertheless, is there anything wrong with the above code that would cause a redirect back to the login page?

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

Very Basic Script. This should work.

add_action('template_redirect', 'redirect_to_login');

function redirect_to_login(){
 if(!is_user_logged_in()){
   // user not logged in so redirect them to login page
   $redirect_url = '' // you can determine where to redirect user after they login
   wp_redirect( wp_login_url($redirect_url), 301 ); exit;
 }
}
share|improve this answer
add comment

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.