函数文档

wp_set_password()

💡 云策文档标注

概述

wp_set_password() 函数用于更新用户的密码,通过哈希处理新密码并存储到数据库。该函数主要用于一次性应用,不当使用可能导致密码重置循环。

关键要点

  • 函数功能:更新指定用户 ID 的密码,使用 wp_hash_password() 进行哈希处理。
  • 参数:$password(明文新密码,字符串,必需),$user_id(用户 ID,整数,必需)。
  • 注意事项:应谨慎使用,避免在插件或主题中频繁调用,以防每次页面加载都重置密码。
  • 钩子:触发 wp_set_password 动作,传递密码、用户 ID 和更新前的用户数据。
  • 相关函数:包括 wp_hash_password()、clean_user_cache()、wpdb::update() 等。

代码示例

// 示例:更新用户密码(注意:此代码应在单次页面加载后删除)
wp_set_password( 'new_password', 123 );

注意事项

  • 此函数默认使用 bcrypt 哈希算法(自 6.8.0 版本起),替代了之前的 phpass。
  • 为与其他应用集成,可覆盖此函数以使用不同的密码检查算法。
  • 调用后会清理用户缓存,并触发 wp_set_password 动作钩子。

📄 原文内容

Updates the user’s password with a new hashed one.

Description

For integration with other applications, this function can be overwritten to instead use the other package password checking algorithm.

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.

Parameters

$passwordstringrequired
The plaintext new user password.
$user_idintrequired
User ID.

Source

function wp_set_password(
	#[SensitiveParameter]
	$password,
	$user_id
) {
	global $wpdb;

	$old_user_data = get_userdata( $user_id );

	$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
	 * @since 6.7.0 The `$old_user_data` parameter was added.
	 *
	 * @param string  $password      The plaintext password just set.
	 * @param int     $user_id       The ID of the user whose password was just set.
	 * @param WP_User $old_user_data Object containing user's data prior to update.
	 */
	do_action( 'wp_set_password', $password, $user_id, $old_user_data );
}

Hooks

do_action( ‘wp_set_password’, string $password, int $user_id, WP_User $old_user_data )

Fires after the user password is set.

Changelog

Version Description
6.8.0 The password is now hashed using bcrypt by default instead of phpass.
2.5.0 Introduced.

User Contributed Notes