WordPress has two registration fields for the default form, email and username. If you need more information, you could use plugins ofcourse. But for some simple fields such as a Name or Full name or Age of the registrants, you might not want to use a plugin. Here is how you can do that.
Add Extra Registration Fields
We will add three new fields, First name, Last Name, Preview Name. However, these fields are already in use within WordPress, but they did not used it on register form.
add_action( 'register_form', 'w4dev_register_form' ); function w4dev_register_form() { $fields = array( 'display_name' => 'Preview 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. Thus, we are generating errors using 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' => 'Preview 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, __( 'ERROR: Please enter your '. $v ) ); } } } return $errors; }
Saving Field Informations
As said earlier, these are some field that WordPress already use for a user. And we can just pass the value to wp_update_user function to update it. But, if you are using any other custom field name, you will need to use update_user_meta
function.
user_register
hook becomes available just after a new user record has been created, thus a $user_id
variable is passed to the hooked function.
add_action( 'user_register', 'w4dev_user_register' ); function w4dev_registration_errors( $user_id ) { $user_data = array(); if( isset($_POST['w4dev_register_fields']) ) { foreach( array( 'display_name', 'first_name', 'last_name') as $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 on your themes functions.php file or within your plugin.