Add custom field below order notes

The official WooCommerce documentation shows you how to add custom fields to the billing or shipping section of the checkout.

This guide shows you how to add fields in the Order Notes section of the checkout.

Add the following 4 parts of code to your functions.php

PART 1 OF 4 – This creates the field on the checkout page below Order Notes. Change the ‘required’ value if this field is optional (and Skip Part 2)

// ADD CUSTOM FIELD BELOW ORDER NOTES 
// PART 1 OF 4
add_action( 'woocommerce_after_order_notes', function ( $checkout ) {
  $date = new DateTime();
  $date->modify("+7 day");

  woocommerce_form_field( 'order_required_by', array(
    'type'          => 'text',
    'class'         => array('form-row-wide'),
    'label'         => __('Date Order Needed By'),
    'placeholder'   => __('Ex: '.$date->format("d-m-Y")),
    'required'      => true,
  ), $checkout->get_value( 'order_required_by' ));

  echo '<em>Do you need this order delivered for a specific date? If so, let us know.<br >Make sure to chose an appropriate delivery method to make sure your order arrives in time.</em>';

} );

PART 2 OF 4 – This validates the field has information set. Skip this if the field is optional.

// ADD CUSTOM FIELD BELOW ORDER NOTES
// PART 2 OF 4
add_action('woocommerce_checkout_process', function () {
  // Check if the field is set, if not then show an error message.
  if ( ! $_POST['order_required_by'] )
    wc_add_notice( __( 'Please let us know when your order is required by.' ), 'error' );
} );

 

PART 3 OF 4 – This saves the data to the order for store owners to see in the order admin.

// ADD CUSTOM FIELD BELOW ORDER NOTES
// PART 3 OF 4
add_action( 'woocommerce_checkout_update_order_meta', function ( $order_id ) {
  if ( ! empty( $_POST['order_required_by'] ) ) {
    update_post_meta( $order_id, 'Order Required By', sanitize_text_field( $_POST['some_field_name'] ) );	}
} );

 

PART 4 OF 4 – Optionally add this information to the emails.

// ADD CUSTOM FIELD BELOW ORDER NOTES
// PART 4 OF 4
add_filter( 'woocommerce_email_order_meta_keys', function () {
  if (get_post_meta( get_the_ID(), 'Some Field')) {
    echo 'Order Required By: ' . get_post_meta( get_the_ID(), 'Order Required By', true) . '<br />';
  }
} );

 


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.