Hi I am Avinash Dahariya. I lead WordPress development at Globussoft and have 2+ years of experience working on various CMS platforms.

In this article I will be showing you how to add a custom field to a WooCommerce product checkout. I will go through adding a custom field on the checkout page.

To add a custom field, we’d go through the following steps:custom_field

  1. Adding custom field
  2. Validating custom field
  3. Updating custom field
  4. Displaying field value on the order page(admin section)

Step-1: Adding a Custom Field

The first step in creating a custom field would be to define the field on the checkout page. Luckily, WooCommerce makes this very easy with its large array of hooks available for use as well as built-in functions to generate HTML input fields. Place the following code inside your theme’s functions .php file to define a new custom field on the checkout page.

/**
* Add custom field on checkout
**/

add_action('woocommerce_after_order_notes', 'custom_checkout_field');

function custom_checkout_field( $checkout ) {
    echo '<div id="additional_information"><h2>'.__('Additional Information').'</h2>';
    woocommerce_form_field( 'additional_information_field', array(
        'type'          => 'text',
        'class'         => array('my-field-class form-row-wide'),
        'label'         => __('Fill in this field'),
        'placeholder'   => __('Enter something'),
    ), $checkout->get_value( 'additional_information_field' ));

    echo '</div>';
}

w1

 

Step-2: Validating the Custom Field

The second step  is to validate the custom field like every other fields in the page.

/**
* Validate the additional_information_field
**/

add_action('woocommerce_checkout_process', 'custom_checkout_field_validation');

function custom_checkout_field_validation() {
    global $woocommerce;
    if (!$_POST['additional_information_field'])
    $woocommerce->add_error( __('<strong>Additional Information</strong> is a required field.') );
}

w2

 

Step-3: Updating Custom Field

After validating the custom field we have to update the order meta.

 

/**
* Update the order meta with additional_information_field value
**/
add_action('woocommerce_checkout_update_order_meta', 'custom_checkout_field_update');

function custom_checkout_field_update( $order_id ) {
    if ($_POST['additional_information_field']) update_post_meta( $order_id, 'Additional Information', esc_attr($_POST['additional_information_field']));
}

w3

 

Step-4: Displaying Field Value on the Order Page (Admin Section)

Finally, added information would be shown here

w4

 

Hope, the article was useful to you. Please, do share your ideas here.