This guide shows you how to add a custom select field (drop-down list) to the registration form on the my account page. In this specific guide, we ask the user for their preferred holiday destination as our dummy example is in the context of a holiday website. You could use this code to implement a select field to capture customer information which will make your demographic data much richer.
/**
* Snippet Name: WooCommerce Custom Select Field On Registration Form
* Snippet Author: ecommercehints.com
*/
// Create the new select drop down list field
add_action( 'woocommerce_register_form', 'ecommercehints_register_select_form_field' );
function ecommercehints_register_select_form_field() {
woocommerce_form_field(
'preferred_holiday_destination',
array(
'type' => 'select',
'required' => true, // Shows an asterisk if true (*)
'label' => 'Preferred Holiday Destination',
'options' => array(
'' => 'Please select...',
'London' => 'London', //
'Ibiza' => 'Ibiza'
)
),
( isset($_POST['preferred_holiday_destination']) ? $_POST['preferred_holiday_destination'] : '' )
);
}
// Show an error if select field is not filled out when registering
add_action( 'woocommerce_register_post', 'ecommercehints_validate_select_field', 10, 3 );
function ecommercehints_validate_select_field( $username, $email, $errors ) {
if ( empty( $_POST['preferred_holiday_destination'] ) ) {
$errors->add( 'preferred_holiday_destination_error', 'We need to store this information to send you the right offers!' );
}
}
// Save the select field as User Meta
add_action( 'woocommerce_created_customer', 'ecommercehints_save_select_field' );
function ecommercehints_save_select_field( $customer_id ){
if ( isset( $_POST['preferred_holiday_destination'] ) ) {
update_user_meta( $customer_id, 'preferred_holiday_destination', wc_clean( $_POST['preferred_holiday_destination'] ) );
}
}
// Show select 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 Select Field Is Left Blank

WordPress User Profile Editor Showing The Saved Select Field Option
