函数文档

wp_is_password_reset_allowed_for_user()

💡 云策文档标注

概述

wp_is_password_reset_allowed_for_user() 函数用于检查特定用户是否允许重置密码。它接受用户 ID 或 WP_User 对象作为参数,返回布尔值或 WP_Error,并包含一个过滤器钩子 allow_password_reset 用于自定义逻辑。

关键要点

  • 函数参数:$user(必需),可以是整数用户 ID 或 WP_User 对象。
  • 返回值:如果允许重置密码则返回 true,否则返回 false 或 WP_Error。
  • 内部逻辑:检查用户是否存在,在 Multisite 环境中还会检查用户是否为垃圾用户(通过 is_user_spammy())。
  • 过滤器钩子:apply_filters('allow_password_reset', $allow, $user->ID) 允许开发者自定义密码重置权限。
  • 相关函数:包括 is_user_spammy()、get_userdata()、is_multisite() 和 apply_filters()。

代码示例

add_filter( 'allow_password_reset', 'wpdocs_disallow_password_reset' );

function wpdocs_disallow_password_reset( $allow, $user_id ) {
	$user = get_userdata( $user_id );
	
	if ( in_array( 'author', (array) $user->roles ) ) {
		return false;
	} 

	return $allow;
}

注意事项

  • 函数在 WordPress 6.3.0 版本中引入。
  • 在 Multisite 安装中,如果用户被标记为垃圾用户,密码重置将被禁止。
  • 可以通过 allow_password_reset 过滤器钩子扩展或修改默认行为,例如基于用户角色限制重置权限。

📄 原文内容

Checks if password reset is allowed for a specific user.

Parameters

$userint|WP_Userrequired
The user to check.

Return

bool|WP_Error True if allowed, false or WP_Error otherwise.

Source

function wp_is_password_reset_allowed_for_user( $user ) {
	if ( ! is_object( $user ) ) {
		$user = get_userdata( $user );
	}

	if ( ! $user || ! $user->exists() ) {
		return false;
	}
	$allow = true;
	if ( is_multisite() && is_user_spammy( $user ) ) {
		$allow = false;
	}

	/**
	 * Filters whether to allow a password to be reset.
	 *
	 * @since 2.7.0
	 *
	 * @param bool $allow   Whether to allow the password to be reset. Default true.
	 * @param int  $user_id The ID of the user attempting to reset a password.
	 */
	return apply_filters( 'allow_password_reset', $allow, $user->ID );
}

Hooks

apply_filters( ‘allow_password_reset’, bool $allow, int $user_id )

Filters whether to allow a password to be reset.

Changelog

Version Description
6.3.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    You can prevent specific user roles from reseting passwords using this filter like below

    add_filter( 'allow_password_reset', 'wpdocs_disallow_password_reset' );
    
    function wpdocs_disallow_password_reset( $allow, $user_id ) {
    	$user = get_userdata( $user_id );
    	
    	if ( in_array( 'author', (array) $user->roles ) ) {
    		return false;
    	} 
    
    	return $allow;
    }