/**
* Update a user's password by user ID, email, or username.
*
* @param int|string $identifier User ID (int), email (string), or username (string).
* @param string $new_password Plaintext new password.
* @return int|\WP_Error Returns the user ID on success or a WP_Error on failure.
*/
function di_update_user_password( $identifier, string $new_password ) {
if ( empty( $new_password ) ) {
return new WP_Error( 'empty_password', 'Password cannot be empty.' );
}
// Resolve the user by identifier.
if ( is_numeric( $identifier ) ) {
$user = get_user_by( 'id', absint( $identifier ) );
} elseif ( is_email( $identifier ) ) {
$user = get_user_by( 'email', $identifier );
} else {
$user = get_user_by( 'login', $identifier );
}
if ( ! $user || ! $user->ID ) {
return new WP_Error( 'user_not_found', 'No matching user found.' );
}
// Option A (recommended for one-off resets): hash + set + reset sessions.
// WordPress will hash internally; do NOT hash yourself.
wp_set_password( $new_password, $user->ID ); // void
// Optionally, return the ID for consistency with wp_update_user().
return (int) $user->ID;
// --- Option B (alternative): use wp_update_user() ---
// $result = wp_update_user( [
// 'ID' => $user->ID,
// 'user_pass' => $new_password, // Pass plaintext; WP hashes it.
// ] );
// return $result; // int|WP_Error
}
place it in your theme’s functions.php or a utilities plugin.
call like this
// By ID
di_update_user_password( 123, 'NewStrongPass!2025' );
// By email
di_update_user_password( '[email protected]', 'Another$trongOne' );
// By username
di_update_user_password( 'maidul', 'S3cure#Pass' );