Security PHP Intermediate

Require Stronger Passwords

Reject passwords shorter than 12 characters or containing the username when users set or reset their password.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 25 lines
function nahnu_password_problem( string $password, string $login ): ?string {
	if ( strlen( $password ) < 12 ) {
		return 'Please use a password of at least 12 characters.';
	}
	if ( '' !== $login && false !== stripos( $password, $login ) ) {
		return 'Your password can\'t contain your username.';
	}
	return null;
}

// Profile screen and Add New User.
add_action( 'user_profile_update_errors', function ( WP_Error $errors, bool $update, $user ): void {
	$pass = (string) wp_unslash( $_POST['pass1'] ?? '' );
	if ( '' !== $pass && ( $msg = nahnu_password_problem( $pass, (string) ( $user->user_login ?? '' ) ) ) ) {
		$errors->add( 'nahnu_weak_password', '<strong>Error:</strong> ' . $msg );
	}
}, 10, 3 );

// "Reset password" form.
add_action( 'validate_password_reset', function ( WP_Error $errors, $user ): void {
	$pass = (string) wp_unslash( $_POST['pass1'] ?? '' );
	if ( '' !== $pass && $user instanceof WP_User && ( $msg = nahnu_password_problem( $pass, $user->user_login ) ) ) {
		$errors->add( 'nahnu_weak_password', $msg );
	}
}, 10, 2 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

WordPress warns about weak passwords but lets people tick “Confirm use of weak password” and carry on. This snippet sets a real minimum: at least 12 characters, and not containing the username.

How it works

WordPress runs user_profile_update_errors when a profile is saved or a user is added in wp-admin, and validate_password_reset on the reset password form. Adding an error to either stops the save and shows the message.

Length matters far more than symbols. A 12-character minimum blocks the short passwords attackers guess first, without forcing hard-to-remember rules.

Things to watch

  • Existing passwords aren’t checked until users change them.
  • WooCommerce’s My Account and checkout account forms use their own validation. Use the woocommerce_min_password_strength filter for those.

How to test it

Edit your profile and try a 6-character password, ticking “Confirm use of weak password”. Saving should fail with the 12-character message.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only