0

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?

1 Answer 1

1

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;
 }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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