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!
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 homepageYou could add another condition there,
is_home()
oris_front_page()
, depending on the setting in admin, but i recommend a longer approach for better compatibilitya) 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 usedb) Use
auth_redirect()
which makes sure user is redirected back to the previous pagec) Use
wp
hook and notinit
since the conditional is_front_page() will not work as $wp_query global has not been set yet.Add another condition: