First and Last Name on the Registration Form
Asks for first and last name when people register through the WordPress form and saves them to the new profile.
Opens WPIDE on
Code
add_action( 'register_form', function () {
$first = isset( $_POST['first_name'] ) ? sanitize_text_field( wp_unslash( $_POST['first_name'] ) ) : '';
$last = isset( $_POST['last_name'] ) ? sanitize_text_field( wp_unslash( $_POST['last_name'] ) ) : '';
?>
<p>
<label for="wpide_first_name">First name</label>
<input type="text" name="first_name" id="wpide_first_name" class="input" value="<?php echo esc_attr( $first ); ?>" autocomplete="given-name" required>
</p>
<p>
<label for="wpide_last_name">Last name</label>
<input type="text" name="last_name" id="wpide_last_name" class="input" value="<?php echo esc_attr( $last ); ?>" autocomplete="family-name" required>
</p>
<?php
} );
add_filter( 'registration_errors', function ( $errors ) {
if ( empty( $_POST['first_name'] ) || empty( $_POST['last_name'] ) ) {
$errors->add( 'wpide_names', '<strong>Error:</strong> Please enter your first and last name.' );
}
return $errors;
} );
add_action( 'user_register', function ( $user_id ) {
if ( ! empty( $_POST['first_name'] ) && ! empty( $_POST['last_name'] ) && 'wp-login.php' === ( isset( $GLOBALS['pagenow'] ) ? $GLOBALS['pagenow'] : '' ) ) {
update_user_meta( $user_id, 'first_name', sanitize_text_field( wp_unslash( $_POST['first_name'] ) ) );
update_user_meta( $user_id, 'last_name', sanitize_text_field( wp_unslash( $_POST['last_name'] ) ) );
}
} );
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.