How to add fields to WooCommerce registration form

woo expert

By default, the WooCommerce registration form only asks for the email, but what if you want to ask for more data to be able to register, is it possible?

My account default registration form

The first thing to note is that by default the WooCommerce “My Account” page does not allow registration, so you will need to enable this WooCommerce setting first.

woocommerce setting to allow creation of account

Once you’ve checked that the setting is active, all that’s left is to decide which field you want to add to the WooCommerce registration form and create a function like this:

/* Extra field register My account */ add_action( 'woocommerce_register_form', 'wphelp_new_field_register_woo' ); function wphelp_new_field_register_woo(){ woocommerce_form_field( 'favorite_food', array( 'type' => 'text', 'required' => true, // This for the field to be required 'label' => 'What is your favorite food?' ), ( isset($_POST['favorite_food']) ? $_POST['favorite_food'] : '' ) ); } //Add field validation add_action( 'woocommerce_register_post', 'wphelp_validate_field', 10, 3 ); function wphelp_validate_field( $username, $email, $errors ) { if ( empty( $_POST['favorite_food'] ) ) { $errors->add( 'error_favorite_food', 'We really want to know!' ); } } //Add field to database add_action( 'woocommerce_created_customer', 'wphelp_save_register_fields' ); function wphelp_save_register_fields( $customer_id ){ if ( isset( $_POST['favorite_food'] ) ) { update_user_meta( $customer_id, 'favorite_food', wc_clean( $_POST['favorite_food'] ) ); } }
Code language: PHP (php)

In the above code we do 3 things:

  • We create a new field in which we ask the user to tell us what their favorite food is. (favorite_food) and the visible text.
  • We add validation to show an error if the field is not filled, making it mandatory.
  • We save the value in the database.

This:

This code that we have seen is ideally added to a customization plugin, or failing that to the functions.php file of the active child theme.

Click to rate this post!
[Total: 0 Average: 0]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top Skip to content