The wp_login_failed
hook is a WordPress action hook that is triggered when a user fails to login to their account. This hook allows developers to perform custom actions or add additional functionality when a login attempt fails.
When a login fails, the wp_login_failed
hook provides developers with the flexibility to handle the error in a way that suits their needs. Some common use cases for this hook include logging failed login attempts, sending notifications to site administrators, or implementing custom redirection for failed logins.
Here’s an example of how to use the wp_login_failed
hook in your WordPress theme’s functions.php file:
function my_custom_login_failed_handler($username) {
// Log the failed login attempt
error_log('Failed login attempt for user: ' . $username);
// Send a notification to the site administrator
$admin_email = get_option('admin_email');
$subject = 'Failed login attempt on your website';
$message = 'Someone tried to login to your website with the username: ' . $username;
wp_mail($admin_email, $subject, $message);
// Redirect the user to a custom page
wp_redirect('/custom-login-failed');
exit;
}
add_action('wp_login_failed', 'my_custom_login_failed_handler');
In this example, the my_custom_login_failed_handler
function is hooked to the wp_login_failed
action. When a login attempt fails, this function will be called. Inside the function, we log the failed login attempt, send a notification to the site administrator, and redirect the user to a custom page.
By using the wp_login_failed
hook, developers can enhance the security and user experience of their WordPress websites by responding to failed login attempts in a customized manner.