Using WordPress ‘random_password’ PHP filter

The ‘random_password’ WordPress PHP filter allows you to modify the randomly generated password that is assigned to a new user when they register on your website.

This filter is useful if you want to customize the password generation process or add additional security measures to your website.

Usage

$new_password = apply_filters( 'random_password', $password, $length, $special_chars, $extra_special_chars );

Parameters

  • $password (string)
    • The generated password.
  • $length (int)
    • The length of password to generate.
  • $special_chars (bool)
    • Whether to include standard special characters.
  • $extra_special_chars (bool)
    • Whether to include other special characters.

Examples

Change Default Password Length

function my_custom_password_length( $password, $length, $special_chars, $extra_special_chars ) {
    // Set the custom password length
    $custom_length = 16;

    // Generate a new password with the custom length
    return wp_generate_password( $custom_length, $special_chars, $extra_special_chars );
}
add_filter( 'random_password', 'my_custom_password_length', 10, 4 );

This code modifies the default password length to 16 characters.

Remove Special Characters from Password

function no_special_chars( $password, $length ) {
    // Generate a new password without special characters
    return wp_generate_password( $length, false, false );
}
add_filter( 'random_password', 'no_special_chars', 10, 2 );

This code generates a password without any special characters.

Include Only Extra Special Characters

function only_extra_special_chars( $password, $length ) {
    // Generate a new password with only extra special characters
    return wp_generate_password( $length, false, true );
}
add_filter( 'random_password', 'only_extra_special_chars', 10, 2 );

This code generates a password with only extra special characters.

Set Custom Password Generation Function

function custom_password_generation( $password, $length, $special_chars, $extra_special_chars ) {
    // Custom password generation logic
    // ...

    return $custom_password;
}
add_filter( 'random_password', 'custom_password_generation', 10, 4 );

This code replaces the default password generation with a custom function.

Make All Passwords Numeric

function numeric_passwords( $password, $length ) {
    // Generate a new password with only numbers
    $numbers = '0123456789';
    return wp_generate_password( $length, false, false, $numbers );
}
add_filter( 'random_password', 'numeric_passwords', 10, 2 );

This code generates a password with only numeric characters.