login_errors
Filters login errors, allowing modification of displayed messages during the login process.
add_filter( 'login_errors', $callback, 10, 1 );
Description
Fires when login errors are displayed. Developers can use this filter to modify or sanitize the login error messages before they are presented to the user, ensuring consistent error handling and preventing potential security issues.
Usage
add_filter( 'login_errors', 'your_function_name', 10, 1 );
Parameters
-
$errors(mixed) - This parameter contains a string of accumulated error messages that will be displayed on the login form.
Return Value
The filtered value.
Examples
<?php
/**
* Modify login error messages to be more user-friendly.
*
* This function hooks into the 'login_errors' filter to change the default
* WordPress login error messages into something more generic and less
* informative to potential attackers.
*
* @param string $errors The original error string generated by WordPress.
* @return string The modified error string.
*/
function my_custom_login_errors( $errors ) {
// Check if the error string is empty, if so, return it as is.
if ( empty( $errors ) ) {
return $errors;
}
// Define a generic error message that can be displayed to the user.
$generic_error_message = __( 'Invalid username or password. Please try again.', 'my-text-domain' );
// If specific error messages are present (like 'Incorrect password'),
// we can potentially customize them further or just return the generic one.
// For simplicity in this example, we'll always return the generic message.
// A more advanced implementation might check for specific error types.
// You could also check for specific error strings and replace them:
// $errors = str_replace( '<strong>ERROR</strong>: ', '', $errors ); // Remove WP's default prefix
// $errors = str_replace( 'Username invalid.', 'The username you entered does not appear to be valid.', $errors ); // Example specific message change
// In this example, we'll just return a single, generic error message.
return $generic_error_message;
}
add_filter( 'login_errors', 'my_custom_login_errors', 10, 1 );
?>
Placement
This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.
Source Code
src/templates/register-form.php:33
$messages .= ' ' . $error . "<br />n";
} else {
$errors .= ' ' . $error . "<br />n";
}
}
}
if ( ! empty( $errors ) ) {
$output .= '<p class="error">' . apply_filters( 'login_errors', $errors ) . "</p>n";
}
if ( ! empty( $messages ) ) {
$output .= '<p class="message">' . apply_filters( 'login_messages', $messages ) . "</p>n";
}
}
}
echo $output;