wp_set_password()WP 2.5.0

Updates the user's password with a new encrypted one. Updates the specified password in the database and resets the user's cache.

Please note: This function should be used sparingly and is really only meant for single-time application. Leveraging this improperly in a plugin or theme could result in an endless loop of password resets if precautions are not taken to ensure it does not execute on every page load.

Pluggable function — this function can be replaced from 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 must-use or regular plugin you can create a function with the same name, then it will replace this function.

Hooks from the function

Return

null. Nothing (null).

Usage

wp_set_password( $password, $user_id );
$password(string) (required)
The plaintext new user password.
$user_id(int) (required)
User ID.

Examples

0

#1 Example of password change (reset) via PHP

Paste the following code into the theme file functions.php, and then go to any page of the site and add to the URL ?set_pass_for=mylogin to activate the function. As a result, the password of the mylogin user will be changed to resetpass. You can then delete the code.

if( isset($_GET['set_pass_for']) ){

	add_action('init', function () {
		$user = get_user_by( 'login', $_GET['set_pass_for'] );
		wp_set_password( 'resetpass', $user->ID ); }
	);

}
0

#2 Change user password programmatically

This code is supposed to be called from the function that should change the password.

$new_pass = trim( wp_unslash( $_POST['new_pass'] ) );
$user_id = 1;

wp_set_password( $new_pass, $user_id );

Notes

  • Global. wpdb. $wpdb WordPress database abstraction object.

Changelog

Since 2.5.0 Introduced.

wp_set_password() code WP 6.5.2

function wp_set_password( $password, $user_id ) {
	global $wpdb;

	$hash = wp_hash_password( $password );
	$wpdb->update(
		$wpdb->users,
		array(
			'user_pass'           => $hash,
			'user_activation_key' => '',
		),
		array( 'ID' => $user_id )
	);

	clean_user_cache( $user_id );

	/**
	 * Fires after the user password is set.
	 *
	 * @since 6.2.0
	 *
	 * @param string $password The plaintext password just set.
	 * @param int    $user_id  The ID of the user whose password was just set.
	 */
	do_action( 'wp_set_password', $password, $user_id );
}