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 have a custom login form working properly on my home view. Nice. But what I want is when user try to view some page, be redirected to my home view instead of wp-login. Im trying to do this way:

add_action('template_redirect', 'redirect_to_login');

function redirect_to_login(){
 if(!is_user_logged_in()){
   wp_redirect(home_url()); exit;
 }
}

It's not working. Browser says it has too many redirects. What can I do?

Thanks!

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

template_redirect is called on every page load including the home page so your code will redirect the user to the homepage even when user is visiting the homepage

You could add another condition there, is_home() or is_front_page(), depending on the setting in admin, but i recommend a longer approach for better compatibility

a) Hook into login_url to change the url for login. This tells wordpress that login form is present on homepage & wp-login.php should not be used

add_filter('login_url', 'change_login_url');
function change_login_url() {
    return home_url('/');
}

b) Use auth_redirect() which makes sure user is redirected back to the previous page
c) Use init hook. This is just a performance bump

add_action('init', 'force_user_login');
function force_user_login() {
    if(!is_user_logged_in())
        auth_redirect();
}
share|improve this answer
add comment

Add another condition:

if( ! is_user_logged_in() and ! is_home() ) {
    # redirect …
}
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.