Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sakilimran/f99639e8907dac96b33b4888a6797a2a to your computer and use it in GitHub Desktop.
Save sakilimran/f99639e8907dac96b33b4888a6797a2a to your computer and use it in GitHub Desktop.
<?php
/**
* Add new register fields for WooCommerce registration.
*/
function wooc_extra_register_fields() {
?>
<p class="form-row form-row-first">
<label for="reg_first_name"><?php _e( 'First name', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="first_name" id="reg_first_name" value="<?php if ( ! empty( $_POST['first_name'] ) ) esc_attr_e( $_POST['first_name'] ); ?>" />
</p>
<p class="form-row form-row-last">
<label for="reg_last_name"><?php _e( 'Last name', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="last_name" id="reg_last_name" value="<?php if ( ! empty( $_POST['last_name'] ) ) esc_attr_e( $_POST['last_name'] ); ?>" />
</p>
<div class="clear"></div>
<?php
}
add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );
/**
* Validate the extra register fields.
*
* @param WP_Error $validation_errors Errors.
* @param string $username Current username.
* @param string $email Current email.
*
* @return WP_Error
*/
function wooc_validate_extra_register_fields( $errors, $username, $email ) {
if ( isset( $_POST['first_name'] ) && empty( $_POST['first_name'] ) ) {
$errors->add( 'first_name_error', __( '<strong>Error</strong>: First name is required!', 'woocommerce' ) );
}
if ( isset( $_POST['last_name'] ) && empty( $_POST['last_name'] ) ) {
$errors->add( 'last_name_error', __( '<strong>Error</strong>: Last name is required!.', 'woocommerce' ) );
}
return $errors;
}
add_filter( 'woocommerce_registration_errors', 'wooc_validate_extra_register_fields', 10, 3 );
/**
* Save the extra register fields.
*
* @param int $customer_id Current customer ID.
*/
function wooc_save_extra_register_fields( $customer_id ) {
if ( isset( $_POST['first_name'] ) ) {
// WordPress default first name field.
update_user_meta( $customer_id, 'first_name', sanitize_text_field( $_POST['first_name'] ) );
}
if ( isset( $_POST['last_name'] ) ) {
// WordPress default last name field.
update_user_meta( $customer_id, 'last_name', sanitize_text_field( $_POST['last_name'] ) );
}
}
add_action( 'woocommerce_created_customer', 'wooc_save_extra_register_fields' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment