Upcoming changes to the “random_password” hook in WordPress 5.3

One of my clients uses very strict requirement for WordPress user passwords. A while ago, I was writing a plugin to enforce those requirements, and found that a small percentage of WordPress’s own password suggestions did not meet these requirements.

For users, accepting a suggested password, and then having it rejected on save is bad UI, so I looked into filtering the suggestions. Like so many things in WordPress, there is a hook for that: random_password. It runs at the end of wp_generate_password, and allows you to modify or replace the password that that function just generated.

The wp_generate_password function receives three arguments.

  • The length of the password to be generated
  • Whether or not to use special characters
  • Whether or not to use “extra special” characters

Unfortunately, the only value passed to the filter hook is the new password. If you write a function for this hook, you have no way of knowing what was originally requested from wp_generate_password.

This would not be a problem is the wp_generate_password function was only used for passwords, as its name would suggest. Instead, it’s also used to create tokens that need to be URL safe, and thus can not contain special characters.

  • The default characters are just lowercase and uppercase letters, and numbers.
  • When the second argument is true, this adds !@#$%^&*() .
  • The extra special characters are -_ []{}<>~`+=,.;:/?| .

This is why I proposed to add additional arguments to the random_password hook. This patch has been accepted into WordPress 5.3, making the hook much more useful. Here’s what it does.

Previously, a typical hook callback for random_password would look like this:

function filter_random_password( $password ) { 
    // do stuff to the password here
    // no way to tell if (extra) special chars are allowed
    return $password; 
}; 

add_filter( 'random_password', 'filter_random_password', 10, 1 );Code language: PHP (php)

Starting with WordPress 5.3, this becomes:

function filter_random_password( $password, $length, $special_chars, $extra_special_chars ) { 
    // do stuff to the password here
    // perfectly clear which chars are allowed
    return $password; 
}; 

add_filter( 'random_password', 'filter_random_password', 10, 4 ); Code language: PHP (php)

As with all WordPress filter hooks, only the first argument is required, so all of this is completely optional, and no existing code should break.

Roy Tanck
I'm a freelance WordPress developer, designer, consultant, meetup organizer and speaker. In my spare time I love to go out and take pictures of things.