This guide shows you how you can implement a custom date picker field on the My Account registration form in WooCoomerce and save the data as User Meta shown in User Profile Editor in the Dashboard. The date is saved to the database. We’ve also implemented two validation methods. This particular guide asks for the user’s date of birth which is saved as user meta. We’ve made the field required so it must be entered. An error will show if the custom date of birth field is left blank. An error will also show if the user enters a date of birth later than the year of 2005.
/**
* Snippet Name: WooCommerce Date Of Birth Field On Registration Form
* Snippet Author: ecommercehints.com
*/
// Create the new Date Of Birth field
add_action( 'woocommerce_register_form', 'ecommercehints_register_date_form_field' );
function ecommercehints_register_date_form_field(){
woocommerce_form_field(
'date_of_birth',
array(
'type' => 'date',
'required' => true, // Shows an asterisk if true (*)
'label' => 'Date Of Birth'
),
( isset($_POST['date_of_birth']) ? $_POST['date_of_birth'] : '' )
);
}
// Show an error if Date Of Birth is not filled out when registering
add_action( 'woocommerce_register_post', 'ecommercehints_validate_dob', 10, 3 );
function ecommercehints_validate_dob( $username, $email, $errors ) {
if ( empty( $_POST['date_of_birth'] ) ) {
$errors->add( 'date_of_birth_error', 'We need to store this information to send you a birthday card.' );
}
if($_POST['date_of_birth'] > 2005) {
$errors->add( 'date_of_birth_error', 'You must be born in 2006 or earlier' );
}
}
// Save the Date Of Birth field as User Meta
add_action( 'woocommerce_created_customer', 'ecommercehints_save_dob_field' );
function ecommercehints_save_dob_field( $customer_id ){
if ( isset( $_POST['date_of_birth'] ) ) {
update_user_meta( $customer_id, 'date_of_birth', wc_clean( date("d/m/Y", strtotime($_POST['date_of_birth'])) ) );
}
}
// Show Date Of Birth field in the User Editor
add_action('show_user_profile', 'custom_user_profile_fields');
add_action('edit_user_profile', 'custom_user_profile_fields');
function custom_user_profile_fields( $user ) { ?>
Custom user meta fields
Validation Error If the Date Field Is Left Blank

Validation Error If the Date Field Is Not Before A Specific Year

WooCommerce/WordPress User Profile Editor Showing Saved Date Field As User Meta
