Random number for user registering on my site

When someone registers on my site, I want it to automatically assign username. eg. A username followed by 4 random numbers.

  • Majid

    Hello Wiztech,

    The following action hook can achieve the results you want. it will take the userame set by the user in the registration form, and add the 4 digits random number.

    For example a username Wiztech will become Wiztech_XXXX
    The only problem with this is that the user won't be able to login with the username he set, you can send them a follow up email with the new generated username.

    function user_random_number( $user_id ) {
    	global $wpdb;
    	// Get registered user's Data
    	$user = get_userdata( $user_id );
    
    	// Generate a 4digits Random Number
    	$random = rand( 1000, 9999 );
    
    	// Update Database with the new user login and user nicename
    	$wpdb->update(
    		$wpdb->users,
    		array(
    			'user_login' => $user->user_login . '_' . $random,
    			'user_nicename' => $user->user_nicename . '_' . $random
    		),
    		array(
    			'ID' => $user_id
    		)
    	);
    }
    add_action( 'user_register', 'user_random_number' );

    Let me know if this helps.

    Thanks,
    Majid

  • Majid

    Hi again,

    I was able to make this work for your theme custom registration form. adding the following code to the bottom of your functions.php will get you the results you want.

    function user_random_number( $user ) {
        global $wpdb;
    
        // Generate a 4digits Random Number
        $rand = rand( 1000, 9999 );
        if( in_array( 'cs_candidate', $user->roles ) ) {
            $rand = 'PRO' . $rand;
        } else if( in_array( 'cs_employer', $user->roles ) ) {
            $rand = 'BIZ' . $rand;
        }
    
        // Update Database with the new user login and user nicename
        $wpdb->update(
            $wpdb->users,
            array(
                'user_login' => $user->user_login . '_' . $rand,
                'user_nicename' => $user->user_nicename . '_' . $rand
            ),
            array(
                'ID' => $user->ID
            )
        );
    }
    add_action( 'jobhunt_candidate_register', 'user_random_number', 11 );
    add_action( 'jobhunt_employer_register', 'user_random_number', 11 );

    Or you can activate the attached JobCareer child theme which is recommended.

    Cheers,
    Majid