In the earlier article WordPress custom registration/login and redirecting users to a front-end user center after login, I introduced a method for replacing the default login page with a custom login page. That article did not solve the problem of removing direct access to wp-login.php. Today, while reviewing the source code of a theme, I found a practical solution.
Redirect wp-login.php to a custom login page
The method is actually very simple. During WordPress initialization, add a function that checks GET requests to wp-login.php, then redirect those requests to your custom login page. Why check only GET requests and not POST requests as well? Because a custom login form still needs to send registration and login data to wp-login.php. If POST requests are redirected too, backend login will obviously stop working. Of course, if you have implemented your own custom handler for registration and login requests elsewhere, then you can redirect POST requests to wp-login.php as well.
add_action('init', function(){
$page_viewed = basename($_SERVER['REQUEST_URI']);
if ($page_viewed === "wp-login.php" && $_SERVER['REQUEST_METHOD'] === 'GET'){
wp_redirect(home_url());
exit;
}
});
Redirect to the custom login page after a login failure
After a login failure, that case also needs to be handled so the user is redirected to a custom login failure page.
add_action('wp_login_failed', function(){
wp_redirect(home_url('?login=failed'));
exit;
});
Redirect to the custom login page after logout
Then there is the logout redirect. We can redirect the user to the homepage after logout, or to a custom error page if needed.
add_action('wp_logout', function(){
wp_redirect(home_url('?login=failed'));
exit;
});
