Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mahdiyazdani/8caba6211d260e959a65166925981919 to your computer and use it in GitHub Desktop.
Save mahdiyazdani/8caba6211d260e959a65166925981919 to your computer and use it in GitHub Desktop.
Add custom fields in user registration WooCommerce
<?php
/**
* Displaying first name and last name fields on
* WooCommerce's registration page.
*/
function woocommerce_register_form() {
$fields = array(
'first_name' => __('First name', 'woocommerce'),
'last_name' => __('Last name', 'woocommerce')
);
foreach( $fields as $k => $v ): ?>
<p class="form-row form-row-wide">
<label for="<?php echo $k; ?>"><?php echo $v; ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="<?php echo $k; ?>" id="<?php echo $k; ?>" value="<?php
if ( ! empty( $_POST[$k] ) ) echo esc_attr( $_POST[$k] ); ?>" />
</p>
<?php
endforeach;
}
add_action( 'woocommerce_register_form_start', 'woocommerce_register_form' );
/**
* Validate the extra register fields.
*/
function woocommerce_registration_errors( $validation_error, $username, $password, $email )
{
if( !isset($_POST['first_name']) || empty($_POST['first_name']) ){
$validation_error->add('error', 'Please enter your First name');
}
elseif( !isset($_POST['last_name']) || empty($_POST['last_name']) ){
$validation_error->add('error', 'Please enter your Last name');
}
return $validation_error;
}
add_filter( 'woocommerce_process_registration_errors', 'woocommerce_registration_errors', 10, 4 );
/**
* Save the extra register fields.
*/
function woocommerce_new_customer_data( $data ) {
/**
* generate username from first/last name field input
* only if username field is inactive
**/
if ( 'no' !== get_option( 'woocommerce_registration_generate_username' ) || ! empty( $username ) ) :
$username = sanitize_user( wc_clean( $_POST['first_name'] ) );
if( username_exists( $username ) ) :
$username .= sanitize_user( wc_clean( $_POST['last_name'] ) );
endif;
// Ensure username is unique
$append = 1;
$o_username = $username;
while ( username_exists( $username ) ) :
$username = $o_username . $append;
$append ++;
endwhile;
$data['user_login'] = $username;
endif;
/**
* WordPress will automatically insert this information's into database,
* we just need to include it here
**/
$data['first_name'] = wc_clean( $_POST['first_name'] );
$data['last_name'] = wc_clean( $_POST['last_name'] );
return $data;
}
add_filter( 'woocommerce_new_customer_data', 'woocommerce_new_customer_data' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment