How To Add A Field To WooCommerce Registration Form

Here we learn about how to add a field to WooCommerce registration form

1. Create a child theme first and Custom code copied and paste into your child theme’s functions.php file.

2. Follow the below step.

  • WooCommerce -> Settings -> Accounts & Privacy.
  • Enabled ‘Allow customers to create an account during checkout’.

3. Two action hooks allow us to add our field.

  • woocommerce_register_form_start – This hook for the beginning of the form.
  • woocommerce_register_form – This hook for before the “Register” button.

Here is an example of fields in the WooCommerce Edit Account page.

<?php
add_action( 'woocommerce_register_form', 'woo_add_register_form_field' ); 
function woo_add_register_form_field(){	 
  woocommerce_form_field(
    'country_to_visit',
    array(
      'type'        => 'text',
      'required'    => true, // just adds an "*"
      'label'       => 'Country you want to visit the most'
    ),
    ( isset( $_POST['country_to_visit'] ) ? $_POST['country_to_visit'] : '' )
  );	 
}
?>

Validation of this field:

<?php
add_action( 'woocommerce_register_post', 'woo_validate_fields', 10, 3 ); 
function woo_validate_fields( $username, $email, $errors ) {	 
  if ( empty( $_POST['country_to_visit'] ) ) {
    $errors->add( 'country_to_visit_error', 'We really want to know!' );
  }	 
}
?>

Now save the field data into the database.

<?php
add_action( 'woocommerce_created_customer', 'woo_save_register_fields' ); 
function woo_save_register_fields( $customer_id ){	 
  if ( isset( $_POST['country_to_visit'] ) ) {
    update_user_meta( $customer_id, 'country_to_visit', wc_clean( $_POST['country_to_visit'] ) );
  }	 
}
?>

OUTPUT:

Submit a Comment

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

Subscribe

Select Categories