Woocommerce

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:

Rahul Prajapat

I’m Rahul Prajapat. I’m a WordPress developer and Author at TheCodeHubs. I have good skill of Html, CSS, JQuery, SQL, Web API, PSD to HTML/PSD to WordPress, WordPress Theme/Plugin Customization, create or modify short code, customize visual composer short code or integrate new short code with visual composer, can create custom metabox for any post type in WordPress admin.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago