wp_authenticate()
Checks the authorization data of the registered user (login and password) and authorizes it if the check was passed.
This function does nothing itself but passes the username and password to the filter authenticate
. Through this filter, the transmitted username and password are checked, and the user is authorized.
This is a pluggable function, and it can be replaced by a plugin. It means that this function is defined (works) only after all plugins are loaded (included), but before this moment this function has not defined. Therefore, you cannot call this and all functions depended on this function directly from a plugin code. They need to be called on plugins_loaded hook or later, for example on init hook.
Function replacement (override) — in a plugin you can create a function with the same name, then it replace this function.
Hooks from the function
Return
WP_User|WP_Error
. WP_User object if the credentials are valid, otherwise WP_Error.
Usage
wp_authenticate( $username, $password );
- $username(string) (required)
- User's username or email address.
- $password(string) (required)
- User's password.
Examples
#1 Authorize user
Suppose we have a username and password and we need to authorize (login) a user with this data. We can do it like this:
$username = 'truegamer'; $password = 'live_is_a_game'; // Authorize $auth = wp_authenticate( $username, $password ); // Error checking if ( is_wp_error( $auth ) ) { $error_string = $auth->get_error_message(); echo '<div id="message" class="error"><p>' . $error_string . '</p></div>'; } else { echo 'Authorization was successful!'; }
#2 Authorize user by email only
This example shows how to enable user authorization in WordPress only by email.
Since WP 4.5 Wordpress automatically authorizes the user by email or login, i.e. you can pass email into the login field (username parameter). Two functions are responsible for such authorization. Both are hanging on the hook authenticate
in the file /wp-includes/default-filters.php.
add_filter( 'authenticate', 'wp_authenticate_username_password', 20, 3 ); add_filter( 'authenticate', 'wp_authenticate_email_password', 20, 3 );
Thus, to disable authorization by login, but leave authorization by mail, you just need to disable the filter associated with the login:
remove_filter( 'authenticate', 'wp_authenticate_username_password', 20, 3 );
#3 Authorize user by login only (disable auth by email)
To leave authentication as it was before WP 4.5. - only by login, you need to remove new filter associated with email:
remove_filter( 'authenticate', 'wp_authenticate_email_password', 20, 3 );
Changelog
Since 2.5.0 | Introduced. |
Since 4.5.0 | $username now accepts an email address. |