Require Strong Passwords for Editors and Administrators
Requires at least 12 characters with letters, numbers and a symbol or mixed case for users who can edit other people's content.
Opens WPIDE on
Code
$wpide_staff_password_length = 12;
$wpide_password_is_strong = function ( $password ) use ( $wpide_staff_password_length ) {
return strlen( $password ) >= $wpide_staff_password_length
&& preg_match( '/[a-z]/i', $password )
&& preg_match( '/\d/', $password )
&& ( preg_match( '/[^a-z0-9]/i', $password ) || ( preg_match( '/[a-z]/', $password ) && preg_match( '/[A-Z]/', $password ) ) );
};
$wpide_strong_message = sprintf( '<strong>Error:</strong> Staff passwords need at least %d characters, including letters, numbers and a symbol or upper- and lowercase letters.', $wpide_staff_password_length );
add_action( 'user_profile_update_errors', function ( $errors, $update, $user ) use ( $wpide_password_is_strong, $wpide_strong_message ) {
if ( empty( $user->user_pass ) ) {
return;
}
$role = isset( $user->role ) ? $user->role : '';
$is_staff = in_array( $role, array( 'administrator', 'editor' ), true ) || ( ! empty( $user->ID ) && user_can( $user->ID, 'edit_others_posts' ) );
if ( $is_staff && ! $wpide_password_is_strong( $user->user_pass ) ) {
$errors->add( 'wpide_strong_password', $wpide_strong_message );
}
}, 10, 3 );
add_action( 'validate_password_reset', function ( $errors, $user ) use ( $wpide_password_is_strong, $wpide_strong_message ) {
if ( $user instanceof WP_User && ! empty( $_POST['pass1'] ) && user_can( $user, 'edit_others_posts' ) && ! $wpide_password_is_strong( wp_unslash( $_POST['pass1'] ) ) ) {
$errors->add( 'wpide_strong_password', $wpide_strong_message );
}
}, 10, 2 );
Notes
Existing passwords are not checked until the user changes or resets it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.