howto

How to add first and last name to WooCommerce sign up form.

There is a useful PHP snippet here for adding billing first and last name to WooCommerce registration, however I needed to add the first and last name to my WordPress profile first and formost. It’s more important for me to set the WordPress profile name in WordPress and leave the billing names until the customer actually checks out.

/*-------------------------------------------------------*/
 /* Add first and last name to sign up form
 /*-------------------------------------------------------*/

add_action( 'woocommerce_register_form_start', 'bb_register_form' );
 function bb_register_form() {

$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', 'mydomain' ) ?><br />
 <input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr( wp_unslash( $first_name ) ); ?>" size="25" /></label>
 </p>

<p>
 <label for="last_name"><?php _e( 'Last Name', 'mydomain' ) ?><br />
 <input type="text" name="last_name" id="last_name" class="input" value="<?php echo esc_attr( wp_unslash( $last_name ) ); ?>" size="25" /></label>
 </p>

<?php
 }

//2. Add validation. In this case, we make sure first_name is required.
 add_filter( 'registration_errors', 'bb_registration_errors', 10, 3 );
 function bb_registration_errors( $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.', 'mydomain' ) );
 }
 if ( empty( $_POST['last_name'] ) || ! empty( $_POST['last_name'] ) && trim( $_POST['first_name'] ) == '' ) {
 $errors->add( 'last_name_error', __( '<strong>ERROR</strong>: You must include a first name.', 'mydomain' ) );
 }
 return $errors;
 }

//3. Finally, save our extra registration user meta.
 add_action( 'user_register', 'bb_user_register' );
 function bb_user_register( $user_id ) {
 if ( ! empty( $_POST['first_name'] ) ) {
 update_user_meta( $user_id, 'first_name', trim( $_POST['first_name'] ) );
 update_user_meta( $user_id, 'last_name', trim( $_POST['last_name'] ) );
 }
 }
Tags: , , ,
Previous Post
By
Digital Designer / WordPress Theme Developer

Leave a Reply

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