我引用了下面的解决方案(来自这里Force Password Complexity) 实施一定级别的密码安全。它按预期工作,但正在为所有用户角色运行。我不想对基本“订阅者”角色强制使用相同的参数。如何阻止代码针对特定角色运行?(或者,强制它为管理员、编辑等特定角色运行)
add_action(\'user_profile_update_errors\', \'validateProfileUpdate\', 10, 3 );
add_filter(\'registration_errors\', \'validateRegistration\', 10, 3 );
add_action(\'validate_password_reset\', \'validatePasswordReset\', 10, 2 );
function validateProfileUpdate( WP_Error &$errors, $update, &$user ) {
return validateComplexPassword( $errors );
}
function validateRegistration( WP_Error &$errors, $sanitized_user_login, $user_email ) {
return validateComplexPassword( $errors );
}
function validatePasswordReset( WP_Error &$errors, $userData ) {
return validateComplexPassword( $errors );
}
function validateComplexPassword( $errors ) {
$password = ( isset( $_POST[ \'pass1\' ] ) && trim( $_POST[ \'pass1\' ] ) ) ? $_POST[ \'pass1\' ] : null;
if ( empty( $password ) || ( $errors->get_error_data( \'pass\' ) ) )
return $errors;
$passwordValidation = validatePassword($password);
if ( $passwordValidation !== true ) {
$errors->add( "pass", "<strong>ERROR</strong>: " . $passwordValidation . "." );
}
return $errors;
}
function validatePassword($Password) {
//#### Check it\'s greater than 6 Characters
if (strlen($Password) < 6) {
return "Password is too short (" . strlen($Password) . "), please use 6 characters or more.";
}
//#### Test password has uppercase and lowercase letters
if (preg_match("/^(?=.*[a-z])(?=.*[A-Z]).+$/", $Password) !== 1) {
return "Password does not contain a mix of uppercase & lowercase characters.";
}
//#### Test password has mix of letters and numbers
if (preg_match("/^((?=.*[a-z])|(?=.*[A-Z]))(?=.*\\d).+$/", $Password) !== 1) {
return "Password does not contain a mix of letters and numbers.";
}
//#### Password looks good
return true;
}
SO网友:Aboelabbas
您可以排除以下某些角色:
1-创建一个函数以检查当前用户角色是否被排除:
function isPasswordValidationSkipped()
{
// Fill this array with roles that you want to exclude from password validation
$excludedRoles = [\'subscriber\'];
$user = wp_get_current_user();
foreach ($user->roles as $role) {
if(in_array($role, $excludedRoles)) {
return true;
}
}
return false;
}
2-然后在“内部”中使用该函数;validateComplexPassword;像这样:
function validateComplexPassword( $errors ) {
$password = ( isset( $_POST[ \'pass1\' ] ) && trim( $_POST[ \'pass1\' ] ) ) ? $_POST[ \'pass1\' ] : null;
if ( true === isPasswordValidationSkipped() || empty( $password ) || ( $errors->get_error_data( \'pass\' ) ) )
return $errors;
$passwordValidation = validatePassword($password);
if ( $passwordValidation !== true ) {
$errors->add( "pass", "<strong>ERROR</strong>: " . $passwordValidation . "." );
}
return $errors;
}