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("https://wordpress.stackexchange.com/");
}
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();
}