WordPress 登录安全维护指南
1、强制强密码
/**
强制执行强密码策略
覆盖:注册、后台修改密码、找回密码重置
*/
function my_custom_enforce_strong_passwords( $errors, $user_unused = null ) {
// 检查是否有密码提交(pass1 是 WordPress 默认的密码字段名)
if ( isset( $_POST['pass1'] ) && ! empty( $_POST['pass1'] ) ) {
$password = $_POST['pass1'];
// 校验规则定义
$min_length = 12;
$has_uppercase = preg_match( '/[A-Z]/', $password );
$has_lowercase = preg_match( '/[a-z]/', $password );
$has_number = preg_match( '/[0-9]/', $password );
$has_special = preg_match( '/[^a-zA-Z0-9]/', $password );
if ( strlen( $password ) < $min_length || !$has_uppercase || !$has_lowercase || !$has_number || !$has_special ) {
// 根据调用的钩子类型返回错误
// registration_errors 和 user_profile_update_errors 传入的是 WP_Error 对象
if ( is_wp_error( $errors ) ) {
$errors->add( 'weak_password', '安全要求:密码必须至少12位,且包含大小写字母、数字和特殊字符。' );
}
}
}
return $errors;
}
// 1. 针对新用户注册
add_filter( 'registration_errors', 'my_custom_enforce_strong_passwords', 10, 1 );
// 2. 针对个人资料编辑(后台或前台个人中心)
add_filter( 'user_profile_update_errors', 'my_custom_enforce_strong_passwords', 10, 1 );
// 3. 针对找回密码时的重置操作(非常重要!)
add_action( 'validate_password_reset', function( $errors ) {
return my_custom_enforce_strong_passwords( $errors );
}, 10, 1 );

浙公网安备 33010602011771号