Search code examples
phpwordpresswoocommerceregistrationmembership

Automatically generate username based on user ID in WooCommerce


I'm working on a WooCommerce project where each user have an ID number. I would like to use the default WooCommerce username field for this user ID.

When creating an account, can I automatically generate an account username for the customer based on their user ID?

img

Example: User ID = 101, Auto generated Username = 101

Is it possible?

Any help would really be appreciated. Thanks!


Solution

  • First of all, make sure that the following option is checked via the WooCommerce settings

    enter image description here


    Normally than you could use the woocommerce_new_customer_username filter hook to change the generated username.

    Copied from includes/wc-user-functions.php

    /**
     * Filter new customer username.
     *
     * @since 3.7.0
     * @param string $username      Customer username.
     * @param string $email         New customer email address.
     * @param array  $new_user_args Array of new user args, maybe including first and last names.
     * @param string $suffix        Append string to username to make it unique.
     */
    return apply_filters( 'woocommerce_new_customer_username', $username, $email, $new_user_args, $suffix );
    

    However, you want to determine the $username based on the $user_id, but the $user_id is determined after data such as username, email address, etc. has been added via wp_insert_user()


    So the solution is to update the $username based on the $user_id immediately after a user is registered, and this can be done via:

    Copied from wp-includes/user.php (WordPress)

    /**
     * Fires immediately after a new user is registered.
     *
     * @since 1.5.0
     *
     * @param int $user_id User ID.
     */
    do_action( 'user_register', $user_id );
    

    And

    • wpdb - WordPress database access abstraction class.

    • update_user_meta() - Update user meta field based on user ID.


    So you get:

    function action_user_register( $user_id ) {
        global $wpdb;
        
        // Set new name + nickname
        $new_name = 'something_' . $user_id;
        
        // Update user user_login
        $wpdb -> update( $wpdb -> users, 
            array( 'user_login' => $new_name, 'user_nicename' => $new_name, 'display_name' => $new_name ), 
            array( 'ID' => $user_id )
        );
        
        // Update user meta
        update_user_meta( $user_id, 'first_name', $new_name );
        update_user_meta( $user_id, 'nickname', $new_name );
    } 
    add_action( 'user_register', 'action_user_register', 10, 1 );
    

    Note: Know that a customer/user can change some of these adjustments via his profile (my account), if you do not want this, you will have to make additional adjustments.