How to add custom fields to the WordPress registration form

I always used to build wordpress project using custom code whatever is requirement.Here, I have used wordpress hooks to customize the registration form.There are pre built action and filter hooks to customize wordpress in-built registration form.You just need to add following codes in your theme functions.php.

Add the Custom Field on Front End registration

1. Adding custom new form field:

Here, wordpress has in-built action hook register_form to added custom fields to wordpress registration form.

//Add a custom new form field
add_action( 'register_form', 'custom_fields_for_register_form' );
function custom_fields_for_register_form() 
{
$phone_number = ( ! empty( $_POST['custom_name'] ) ) ? trim( $_POST['custom_name'] ) : ''; ?>
<label for="custom_name"><?php _e( 'Custom Name', 'mj' ) ?>
<input type="text" name="custom_name" id="custom_name" class="input" value="<?php echo esc_attr( wp_unslash( $custom_name ) ); ?>" size="25" /></label>
<?php 
}

2. Add validation to registration process:

registration_errors filter hook is used to validate the registration and can be used to implement custom validation rules.This filter is triggered when the form is being submitted and before the user data is saved.

 

//Add validation to registration process
add_filter( ‘registration_errors’, ‘registration_process_validation’, 10, 3 );
function registration_process_validation( $errors, $sanitized_user_login, $user_email ) 
{

if ( empty( $_POST[‘custom_name’] ) || ! empty( $_POST[‘custom_name’] ) && trim( $_POST[‘custom_name’] ) == ” ) {
$errors->add( ‘custom_name_error’, __( ‘<strong>ERROR</strong>: Please enter custom name.’, ‘mj’ ) );
}

return $errors;
}

 

3. Save custom fields value to registered user meta:

user_register acton hook is used to save extra user meta data.This action hook allows you to get data of newly registered data.And user id is used as parameter to save to user meta data.

//Save custom fields value to registered user meta
add_action( ‘user_register’, ‘save_custom_fields_value’ );
function save_custom_fields_value( $user_id ) 
{
if ( ! empty( $_POST[‘custom_name’] ) ) {

update_user_meta( $user_id, ‘custom_name’, trim( $_POST[‘custom_name’] ) );
}
}

 

 

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *