This code snippet allows you to add a custom select field on the WooCommerce registration form.
The user is asked to select their preferred gift for this specific example. If empty, a custom error is shown. If validated properly, the select field is saved to the database as user meta and shown in the user profile editor in the WordPress Dashboard.
// Create the new select drop down list field
add_action( 'woocommerce_register_form', 'wptu_register_select_form_field' );
function wptu_register_select_form_field() {
woocommerce_form_field(
'preferred_gift',
array(
'type' => 'select',
'required' => true, // Shows an asterisk if true (*)
'label' => 'Preferred Gift',
'options' => array(
'' => 'Please select...',
'Hat' => 'Hat',
'Shirt' => 'Shirt',
'Mug' => 'Mug',
)
),
( isset($_POST['preferred_gift']) ? $_POST['preferred_gift'] : '' )
);
}
// Show an error if select field is not filled out when registering
add_action( 'woocommerce_register_post', 'wptu_validate_select_field', 10, 3 );
function wptu_validate_select_field( $username, $email, $errors ) {
if ( empty( $_POST['preferred_gift'] ) ) {
$errors->add( 'preferred_gift_error', 'We need to store this information to send you the right gift!' );
}
}
// Save the select field as User Meta
add_action( 'woocommerce_created_customer', 'wptu_save_select_field' );
function wptu_save_select_field( $customer_id ){
if ( isset( $_POST['preferred_gift'] ) ) {
update_user_meta( $customer_id, 'preferred_gift', wc_clean( $_POST['preferred_gift'] ) );
}
}
// 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 ) { ?>
<h2>Custom user meta fields</h2>
<table class="form-table">
<tr>
<th>
<label for="preferred_gift"><?php _e( 'Preferred Gift' ); ?></label>
</th>
<td>
<input type="text" name="preferred_gift" id="preferred_gift" value="<?php echo esc_attr( get_the_author_meta( 'preferred_gift', $user->ID ) ); ?>" class="regular-text" />
</td>
</tr>
</table>
<?php
}
// Save new select if edited by admin
add_action( 'personal_options_update', 'update_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'update_extra_profile_fields' );
function update_extra_profile_fields( $user_id ) {
if ( current_user_can( 'edit_user', $user_id ) )
update_user_meta( $customer_id, 'preferred_gift', wc_clean( $_POST['preferred_gift'] ) );
}