Created
January 1, 2020 06:52
-
-
Save meetawahab/13af3914dffbf88e204c9fa94e501ea8 to your computer and use it in GitHub Desktop.
Add First Name & Last Name field on the WordPress registration form.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'register_form', 'loginpress_plugin_register_form_custom_field' ); | |
function loginpress_plugin_register_form_custom_field() { | |
$first_name = ( ! empty( $_POST['first_name'] ) ) ? trim( $_POST['first_name'] ) : ''; | |
$last_name = ( ! empty( $_POST['last_name'] ) ) ? trim( $_POST['last_name'] ) : ''; ?> | |
<p> | |
<label for="first_name"> | |
<?php _e( 'First Name', 'loginpress' ) ?><br /> | |
<input type="text" name="first_name" id="first_name" class="input regular_text" value="<?php echo esc_attr( wp_unslash( $first_name ) ); ?>" size="30" /> | |
</label> | |
</p> | |
<p> | |
<label for="last_name"> | |
<?php _e( 'Last Name', 'loginpress' ) ?><br /> | |
<input type="text" name="last_name" id="last_name" class="input regular_text" value="<?php echo esc_attr( wp_unslash( $last_name ) ); ?>" size="30" /> | |
</label> | |
</p> | |
<?php | |
} | |
// 2. Field validation. | |
add_filter( 'registration_errors', 'loginpress_plugin_registration_errors_custom_field', 10, 3 ); | |
function loginpress_plugin_registration_errors_custom_field( $errors, $sanitized_user_login, $user_email ) { | |
if ( empty( $_POST['first_name'] ) || ! empty( $_POST['first_name'] ) && trim( $_POST['first_name'] ) == '' ) { | |
$errors->add( 'first_name_error', __( '<strong>ERROR</strong>: You must include a first name.', 'loginpress' ) ); | |
} | |
if ( empty( $_POST['last_name'] ) || ! empty( $_POST['last_name'] ) && trim( $_POST['last_name'] ) == '' ) { | |
$errors->add( 'last_name_error', __( '<strong>ERROR</strong>: You must include a last name.', 'loginpress' ) ); | |
} | |
return $errors; | |
} | |
// 3. Lastly, save our extra registration user meta. | |
add_action( 'user_register', 'loginpress_plugin_user_register_custom_field' ); | |
function loginpress_plugin_user_register_custom_field( $user_id ) { | |
if ( ! empty( $_POST['first_name'] ) ) { | |
update_user_meta( $user_id, 'first_name', trim( $_POST['first_name'] ) ); | |
} | |
if ( ! empty( $_POST['last_name'] ) ) { | |
update_user_meta( $user_id, 'last_name', trim( $_POST['last_name'] ) ); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment