Forcing Strong Usernames in WordPress

October 2, 2015
Posted in: Code Snippets, Web Development, WordPress

Insecure usernames and passwords are responsible for a large number of system break-ins each year.

Luckily, WordPress now enforces strong passwords – passwords that use a large number of characters including:

  • Lowercase letters
  • Uppercase letters
  • Numbers
  • Special characters

While it’s unlikely that a brute-force attack would get past a secure password, we can heighten security a bit more by using a secure username. WordPress doesn’t allow special characters in usernames, so we’ll stick to letters and numbers.

First thing to do is create a file in your theme named admin.js.

Now we can enqueue it as an admin-only script – just add this code to your theme’s functions.php file:

function add_admin_scripts() {
  wp_enqueue_script("admin-js", get_template_directory_uri() . "/admin.js");
add_action("admin_enqueue_scripts", "add_admin_scripts");


Once that’s in place, confirm that it’s being loaded up when you visit the admin area, then add this code:

jQuery(document).ready(function($) {
	// suggest a secure username
	$('.user-new-php #user_login').each(function() {
		// set the username - 16 character alphanumeric
		$(this).val( Math.random().toString(36).slice(-8) + Math.random().toString(36).slice(-8) );

		// hide the username field

This function builds a username using a random number converted to base 36, then cleaned up a bit include only letters and numbers. It also hides the username field – this line can be removed if you’d still like to have manual control over usernames.

And here’s a slightly more condensed version of the code:

jQuery(document).ready(function($) {
	$('.user-new-php #user_login').val( Math.random().toString(36).slice(-8) + Math.random().toString(36).slice(-8) ).closest('tr.form-field').hide();

Scott Buckingham

President / Owner
613-801-1350 x101
[email protected]
Scott is a WordPress expert who has worked on hundreds of web design and development projects. He excels at finding creative ways to solve technical problems. View full profile