• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

WP Bitz

A curated collection of code snippets for WordPress

  • Home
  • About
  • Blog
  • Code Snippets
You are here: Home / Code Snippets / Override the WP random password generator with custom generator

Override the WP random password generator with custom generator

November 9, 2020

This post brought to you by RocketGeek, ButlerBlog, and the following:

 

 // Override the WP random password generator with a custom random password.
add_filter( 'random_password', 'my_random_password' ); 
function my_random_password() {
    
    // Define password length
    $len = 15;
    
    // Define character sets (lower, upper, numbers, special, extra).
    $chars = array( 'lower', 'upper', 'numbers', 'special' );
    
    // Nothing to change here. Return new value.
    return my_password_generator( $chars, $len );
}

/**
 * Generate a random password.
 * 
 * This utility function can be used as-is, or you can
 * edit/add to the $chars array for custom string sets.
 * 
 * @param array $chars {
 *    @type string $lower   All lowercase characters. 
 *    @type string $upper   All uppercase characters.
 *    @type string $numbers All numbers 0-9,
 *    @type string $special Common special characters.
 *    @type string $extra   Extra special characters.
 *  }
 * @param   $len      string The password length to generate.
 * @return  $password string The generated password.
 */
function my_password_generator( $chars, $len ) {
    
    $available_chars = array(
        'lower'   => 'abcdefghijklmnopqrstuvwxyz',
        'upper'   => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'numbers' => '0123456789',
        'special' => '!@#$%^&*()',
        'extra'   => '-_ []{}<>~`+=,.;:/?|',
    );
    
    $char_string = '';
    foreach( $chars as $char_set ) {
        $char_string .= $available_chars[ $char_set ];
    }
    
    $password = '';
    for( $i = 0; $i < $len; $i++ ) {
        $password .= substr( $char_string, wp_rand( 0, strlen( $char_string ) - 1 ), 1 );
    }
    
    return $password;
}

Chad Butler

Primary Sidebar

Join for free!

Get free code snippets, WordPress best practices, and practical Content Marketing advice from seasoned WordPress expert Chad Butler (butlerblog):

Recent Posts

  • Bitnami WordPress Autoptimize cannot write to the cache directory
  • Create and delete WordPress sites in XAMPP with a batch file
  • How to fix “Error: MySQL Shutdown Unexpectedly” in XAMPP control panel
  • Fix missing Customizer in WordPress 6
  • Use Proofy.io API to validate WordPress registrations

Copyright © 2023 · Maker Pro on Genesis Framework · WordPress · Log in