Skip to content

Instantly share code, notes, and snippets.

@bentasm1
Created January 5, 2016 03:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bentasm1/88f36e00c69dc2f9cf78 to your computer and use it in GitHub Desktop.
Save bentasm1/88f36e00c69dc2f9cf78 to your computer and use it in GitHub Desktop.
WooCommerce - Collect buyers First and Last Name at Registration
/* BEGIN REGISTRATION FIELDS */
function cs_wc_extra_register_fields() {
?>
<p class="form-row form-row-first">
<label for="reg_billing_first_name"><?php _e( 'First Name', 'textdomain' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_first_name" id="reg_billing_first_name" value="<?php if ( ! empty( $_POST['billing_first_name'] ) ) esc_attr_e( $_POST['billing_first_name'] ); ?>" />
</p>
<p class="form-row form-row-last">
<label for="reg_billing_last_name"><?php _e( 'Last Name', 'textdomain' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_last_name" id="reg_billing_last_name" value="<?php if ( ! empty( $_POST['billing_last_name'] ) ) esc_attr_e( $_POST['billing_last_name'] ); ?>" />
</p>
<?php
}
add_action( 'woocommerce_register_form_start', 'cs_wc_extra_register_fields' );
function cs_wc_validate_extra_register_fields( $username, $email, $validation_errors ) {
if ( isset( $_POST['billing_first_name'] ) && empty( $_POST['billing_first_name'] ) ) {
$validation_errors->add( 'billing_first_name_error', __( '<strong>Error</strong>: Required.', 'textdomain' ) );
}
if ( isset( $_POST['billing_last_name'] ) && empty( $_POST['billing_last_name'] ) ) {
$validation_errors->add( 'billing_last_name_error', __( '<strong>Error</strong>: Required.', 'textdomain' ) );
}
}
add_action( 'woocommerce_register_post', 'cs_wc_validate_extra_register_fields', 10, 3 );
function cs_wc_save_extra_register_fields( $customer_id ) {
if ( isset( $_POST['billing_first_name'] ) ) {
update_user_meta( $customer_id, 'first_name', sanitize_text_field( $_POST['billing_first_name'] ) );
update_user_meta( $customer_id, 'billing_first_name', sanitize_text_field( $_POST['billing_first_name'] ) );
}
if ( isset( $_POST['billing_last_name'] ) ) {
update_user_meta( $customer_id, 'last_name', sanitize_text_field( $_POST['billing_last_name'] ) );
update_user_meta( $customer_id, 'billing_last_name', sanitize_text_field( $_POST['billing_last_name'] ) );
}
}
add_action( 'woocommerce_created_customer', 'cs_wc_save_extra_register_fields' );
/* END REGISTRATION FIELDS */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment