How to change the wordpress password via a simple function

I needed to allow users to set their own passwords in a simple website i have been working on.

View the source code


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) );
	
	        wp_cache_delete($user_id, 'users');
}


So you can now run a simple ajax request to change the password


$newPassword = ltrim($_POST['newPassword']);
wp_set_password( $newPassword, $user_id );