Extending WordPress Registration Fields

WordPress has two registration fields on the default form, email and username. If you need more information from registrants, you could use a plugin of course. But for some simple fields such as a Name, Full name or Age, you might not want to use a plugin. Here is how you can do that yourself.


Add Extra Registration Fields

We will add three new fields, First name, Last Name and Display Name. These fields are already in use within WordPress, they are just not shown on the register form.

add_action( 'register_form', 'w4dev_register_form' );
function w4dev_register_form()
{
    $fields = array(
        'display_name' 	=> 'Display name',
        'first_name' 	=> 'First name',
        'last_name' 	=> 'Last name'
    );
    foreach( $fields as $k => $v ){ ?>
        <p><label>
        <?php _e($v) ?>
        <br /><input type="text" name="<?php echo $k ?>" id="wpa_<?php echo $k ?>" class="input" value="" />
        </label></p>
    <?php }
    ?><input type="hidden" name="w4dev_register_fields" value="1" /><?php
}

Validate Additional fields input

We are making sure all of these fields are required and can not be left empty. So we are generating errors using the proper hook, registration_errors.

add_filter( 'registration_errors', 'w4dev_registration_errors', 1, 3 );
function w4dev_registration_errors( $errors, $user_login, $user_email )
{
    $fields = array(
        'display_name' 	=> 'Display name',
        'first_name' 	=> 'First name',
        'last_name' 	=> 'Last name'
    );

    if( isset($_POST['w4dev_register_fields']) )
    {
        foreach( $fields as $k => $v )
        {
            if( ! isset($_POST[$k]) || '' == $_POST[$k] )
            {
                $errors->add( 'empty_'. $k, __( '<strong>ERROR</strong>: Please enter your '. $v ) );
            }
        }
    }
    return $errors;
}

Saving Field Information

As said earlier, these are fields that WordPress already uses for a user. So we can just pass the values to the wp_update_user function to save them. But if you are using any other custom field name, you will need to use the update_user_meta function instead.

The user_register hook becomes available just after a new user record has been created, and a $user_id variable is passed to the hooked function.

add_action( 'user_register', 'w4dev_user_register' );
function w4dev_user_register( $user_id )
{
    $user_data = array();
    if( isset($_POST['w4dev_register_fields']) )
    {
        foreach( array( 'display_name', 'first_name', 'last_name') as $k )
        {
            if( isset($_POST[$k]) )
            {
                $user_data[$k] = wp_unslash( $_POST[$k] );
            }
        }
    }

    if( !empty($user_data) )
    {
        $user_data['ID'] = $user_id;
        wp_update_user( $user_data );
    }
}

All of the code above can go in your theme’s functions.php file or within your plugin.