1

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!

4

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 wp hook and not init since the conditional is_front_page() will not work as $wp_query global has not been set yet.

add_action('wp', 'force_user_login');
function force_user_login() {
    if(!is_user_logged_in())
        auth_redirect();
}
1

Add another condition:

if( ! is_user_logged_in() and ! is_home() ) {
    # redirect …
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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