First and Last Name on the WooCommerce Registration Form
Adds required first and last name fields to the My Account registration form and saves them to the customer's profile and billing details.
Opens WPIDE on
Code
add_action( 'woocommerce_register_form_start', function () {
// phpcs:disable WordPress.Security.NonceVerification -- Repopulating the form after a failed submit.
$first = isset( $_POST['billing_first_name'] ) ? sanitize_text_field( wp_unslash( $_POST['billing_first_name'] ) ) : '';
$last = isset( $_POST['billing_last_name'] ) ? sanitize_text_field( wp_unslash( $_POST['billing_last_name'] ) ) : '';
// phpcs:enable
?>
<p class="form-row form-row-first">
<label for="reg_billing_first_name"><?php echo esc_html( 'First name' ); ?> <span class="required" aria-hidden="true">*</span></label>
<input type="text" class="input-text" name="billing_first_name" id="reg_billing_first_name" autocomplete="given-name" required value="<?php echo esc_attr( $first ); ?>">
</p>
<p class="form-row form-row-last">
<label for="reg_billing_last_name"><?php echo esc_html( 'Last name' ); ?> <span class="required" aria-hidden="true">*</span></label>
<input type="text" class="input-text" name="billing_last_name" id="reg_billing_last_name" autocomplete="family-name" required value="<?php echo esc_attr( $last ); ?>">
</p>
<div class="clear"></div>
<?php
} );
add_filter( 'woocommerce_registration_errors', function ( $errors ) {
// phpcs:disable WordPress.Security.NonceVerification -- WooCommerce verifies the registration nonce.
if ( empty( $_POST['billing_first_name'] ) || '' === trim( sanitize_text_field( wp_unslash( $_POST['billing_first_name'] ) ) ) ) {
$errors->add( 'billing_first_name_error', 'Please enter your first name.' );
}
if ( empty( $_POST['billing_last_name'] ) || '' === trim( sanitize_text_field( wp_unslash( $_POST['billing_last_name'] ) ) ) ) {
$errors->add( 'billing_last_name_error', 'Please enter your last name.' );
}
// phpcs:enable
return $errors;
} );
add_action( 'woocommerce_created_customer', function ( $customer_id ) {
// phpcs:disable WordPress.Security.NonceVerification -- WooCommerce verifies the registration nonce.
foreach ( array( 'first_name', 'last_name' ) as $field ) {
if ( isset( $_POST[ 'billing_' . $field ] ) ) {
$value = sanitize_text_field( wp_unslash( $_POST[ 'billing_' . $field ] ) );
update_user_meta( $customer_id, $field, $value );
update_user_meta( $customer_id, 'billing_' . $field, $value );
}
}
// phpcs:enable
} );
Notes
Enable "Allow customers to create an account on the My account page" in WooCommerce > Settings > Accounts to see the form.
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.