WordPress at a glance

wp_authenticate() WP 1.0

Authenticate a user, confirming the login credentials are valid.

  • Since 4.5.0 $username now accepts an email address.

This is a pluggable function, and it can be replaced from plugin. It means that this function is defined (works) only after all plugins are connected (included), but before this moment the function has not yet been defined... Therefore, you cannot call this and all functions depended on this function directly from a plugin code. It must be called via hook plugins_loaded or later, for example on hook init.

Function replacement (override) — in a plugin you can create a function with the same name, then it will replace this function.

Is the basis for: wp_signon()
Hooks from 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.

Code of wp_authenticate: wp-includes/pluggable.php VER 4.9.8

<?php
function wp_authenticate($username, $password) {
	$username = sanitize_user($username);
	$password = trim($password);

	/**
	 * Filters whether a set of user login credentials are valid.
	 *
	 * A WP_User object is returned if the credentials authenticate a user.
	 * WP_Error or null otherwise.
	 *
	 * @since 2.8.0
	 * @since 4.5.0 `$username` now accepts an email address.
	 *
	 * @param null|WP_User|WP_Error $user     WP_User if the user is authenticated.
	 *                                        WP_Error or null otherwise.
	 * @param string                $username Username or email address.
	 * @param string                $password User password
	 */
	$user = apply_filters( 'authenticate', null, $username, $password );

	if ( $user == null ) {
		// TODO what should the error message be? (Or would these even happen?)
		// Only needed if all authentication handlers fail to return anything.
		$user = new WP_Error( 'authentication_failed', __( '<strong>ERROR</strong>: Invalid username, email address or incorrect password.' ) );
	}

	$ignore_codes = array('empty_username', 'empty_password');

	if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
		/**
		 * Fires after a user login has failed.
		 *
		 * @since 2.5.0
		 * @since 4.5.0 The value of `$username` can now be an email address.
		 *
		 * @param string $username Username or email address.
		 */
		do_action( 'wp_login_failed', $username );
	}

	return $user;
}

Related Functions

From tag: authenticate (authentication login)

More from category: Login/Logout

No comments
    Hello, !     Log In . Register