WooCommerce is a powerful and flexible eCommerce platform that allows you to create and customize online stores. One of the features that WooCommerce offers is the ability to add and edit custom fields on the checkout page. Custom fields can help you collect additional information from your customers, such as preferences, feedback, delivery instructions, etc.
In this article, HuyHoa will show you how to use the woocommerce_form_field() function to create and customize different types of fields on the checkout page. We will also provide you with 16 sample code snippets that demonstrate how to use this function for various purposes. By the end of this article, you will be able to:
- Customize the HTML structure of woocommerce_form_field()
- Add a placeholder to a field
- Add custom text or HTML under a field
- Display a VAT number for the B2B field on the Checkout Page
- Use woocommerce_form_field() with select options
- Add custom CSS class to WooCommerce checkout fields
- Adding a hidden checkout field in WooCommerce
- Add a checkbox field to the checkout
- Add a custom field to the WooCommerce checkout page
- Add an attribute to woocommerce_form_field
- Set the default value of woocommerce_form_field
- Use woocommerce_form_field() for radio fields
- Change the priority of woocommerce_form_field
- Make WooCommerce checkout page fields read-only
- Use woocommerce_form_field() for date and time fields
- Validate woocommerce_form_field
Let’s get started!
Table of Contents
- 1 Information
- 2 Parameters
- 3 Custom your checkout field with woocommerce_form_field
- 3.1 Customize the HTML structure of woocommerce_form_field()
- 3.2 Add a placeholder to a field
- 3.3 Add custom text or HTML under a field
- 3.4 Display a VAT number for the B2B field on the Checkout Page
- 3.5 woocommerce_form_field() select options
- 3.6 Add custom CSS class to WooCommerce checkout fields
- 3.7 Adding a hidden checkout field in WooCommerce
- 3.8 Add a checkbox field to the checkout
- 3.9 Add a custom field to WooCommerce checkout page by use woocommerce_form_field() function
- 3.10 Add an attribute to woocommerce_form_field
- 3.11 Set the default value of woocommerce_form_field
- 3.12 Woocommerce_form_field radio
- 3.13 Woocommerce_form_field priority
- 3.14 Woocommerce_form_field read-only
- 3.15 Use woocommerce_form_field() for date and time fields
- 3.16 Validate woocommerce_form_field
Information
Function name: woocommerce_form_field
Plugin ref: WooCommerce
Source file: woocommerce/includes/wc-template-functions.php
Called by: woocommerce/templates/checkout/form-billing.php
, woocommerce/templates/checkout/form-shipping.php
, woocommerce/templates/myaccount/form-edit-address.php
Parameters
To use woocommerce_form_field() to create different types of fields, you need to pass three parameters: $key, $args, and $value. The $key is the field name and ID, the $args is an array of field parameters, and the $value is the default or current value of the field.
$key: ( string ) required – Key.
$args: ( mixed ) required – Arguments.
$value: ( string ) optional – (default: null).
$args – Array of field parameters
$args parameters include the following:
type: woocommerce_form_field helps you to create fields of different types. Below is a list of the types of HTML fields it can generate. Surely I don’t need to explain more about these default HTML field types <input type="number" />
anymore, do I?.
Here is the list that this function supports
- text
- select
- radio
- password
- datetime
- datetime-local
- date
- month
- time
- week
- number
- URL
- tel
- country – a dropdown list of countries supported by your store, which are set in WooCommerce settings > General tab. The interesting thing is that depending on the field
$key
parameter it will display a different list of countries. So, if you pass the value of the field equal to shipping_country it will display the countries you ship to (another WooCommerce setting). - state – a dropdown list of states.
country (string): Only for state field types. Name of a country which states you would like to display. If not passed, this field will try to get the states of a billing or shipping country.
label (string): Field label.
description (string): Any custom text (HTML tags are supported too) will be displayed just under а field.
placeholder (string): You can use it to add a placeholder to any supported fields like text and textarea.
maxlength (int): Adds max length HTML attribute to the field. Defaults to false (no attribute added).
required (bool): Do you think it adds the required HTML attribute? Example: <input type="text" required="required" />
No, it doesn’t! All this parameter does is add an asterisk near the field label. If you want to add the required attribute to the input field then read Add an attribute to woocommerce_form_field below
autocomplete: The autocomplete attribute for the field. Possible values are on or off.
id: The ID of the field, if different from the name.
class: An array of custom classes for the field container.
label_class: An array of custom classes for the field label.
input_class: An array of custom classes for the field input.
return: Whether to return or echo the field HTML. The default is false (echo).
options: An array of options for select and radio fields. The format is array('' => 'Select...', 'val1' => 'Title 1')
.
custom_attributes: An array of custom attributes for the field input. The format is array('data-length' => 500)
.
validate: An array of validation classes for the field wrapper. For example, validate-email will validate email addresses using JS.
default: The default value of the field.
autofocus: Whether to autofocus the field or not.
Here are some examples of how to use woocommerce_form_field() for different types of fields:
// Text field woocommerce_form_field( 'my_text_field', array( 'type' => 'text', 'label' => 'My Text Field', 'placeholder' => 'Enter some text', 'required' => true, 'maxlength' => 20, 'input_class' => array('my-text-class'), 'custom_attributes' => array('data-length' => 500), ), $value ); // Select field woocommerce_form_field( 'my_select_field', array( 'type' => 'select', 'label' => 'My Select Field', 'options' => array( '' => 'Select an option', 'option_1' => 'Option 1', 'option_2' => 'Option 2', 'option_3' => 'Option 3', ), ), $value ); // Radio field woocommerce_form_field( 'my_radio_field', array( 'type' => 'radio', 'label' => 'My Radio Field', 'options' => array( 'option_1' => 'Option 1', 'option_2' => 'Option 2', 'option_3' => 'Option 3', ), ), $value );
Custom your checkout field with woocommerce_form_field
$string = woocommerce_form_field( $key, $args, $value );
Some examples of how to use the woocommerce_form_field() function
Customize the HTML structure of woocommerce_form_field()
To customize the HTML structure of woocommerce_form_field(), you need to use the woocommerce_form_field_{$args[‘type’]} filter hook, where {$args[‘type’]} is the type of the field, such as text, select, radio, etc. This filter hook allows you to modify the output HTML of the field according to your needs.
For example, if you want to customize the HTML structure of a radio field, you can use this code:
add_filter( 'woocommerce_form_field_radio', 'custom_form_field_radio', 10, 4 ); function custom_form_field_radio( $field, $key, $args, $value ) { // Do something with the field HTML return $field; }
The $field variable contains all HTML from <p> to the closing </p> tag, so you can rewrite the entire output of this through your function.
Let’s say you want to customize the HTML structure of a text field. You can use this code:
add_filter( 'woocommerce_form_field_text', 'custom_form_field_text', 10, 4 ); function custom_form_field_text( $field, $key, $args, $value ) { // Replace the <p> tag with a <div> tag $field = str_replace( '<p', '<div', $field ); $field = str_replace( '</p>', '</div>', $field ); // Add a custom class to the input tag $field = str_replace( 'input-text', 'input-text custom-class', $field ); // Add a custom attribute to the input tag $field = str_replace( '/>', 'data-custom="true" />', $field ); return $field; }
This will change the output HTML of the text field to something like this:
<div class="form-row form-row-wide" id="my_text_field_field" data-priority=""> <label for="my_text_field" class="">My Text Field <span class="optional">(optional)</span></label> <span class="woocommerce-input-wrapper"> <input type="text" class="input-text custom-class" name="my_text_field" id="my_text_field" placeholder="" value="" data-custom="true" /> </span> </div>
Add a placeholder to a field
To add a placeholder to a field, you need to include the placeholder parameter in the $args array of the woocommerce_form_field() function. The value of the placeholder parameter should be the text that you want to display as the placeholder.
For example, if you want to add a placeholder to a text field, you can use this code:
woocommerce_form_field( 'my_text_field', array( 'type' => 'text', 'label' => 'My Text Field', 'placeholder' => 'Enter some text', ), $value );
This will create a text field with the label “My Text Field” and the placeholder “Enter some text”.
You can use the placeholder parameter for any supported field types, such as text, textarea, email, password, etc.
Add custom text or HTML under a field
To add custom text or HTML under a field, you need to include the description parameter in the $args array of the woocommerce_form_field() function. The value of the description parameter should be the text or HTML that you want to display under the field.
For example, if you want to add some custom text under a text field, you can use this code:
woocommerce_form_field( 'my_text_field', array( 'type' => 'text', 'label' => 'My Text Field', 'description' => 'This is some custom text under the field.', ), $value );
This will create a text field with the label “My Text Field” and the description “This is some custom text under the field.”
You can use the description parameter for any supported field types, and you can also use HTML tags to format your description.
Display a VAT number for the B2B field on the Checkout Page
Add this code snippet to functions.php in your theme. It will add a VAT number for the B2B field on Checkout Page.
add_action( 'woocommerce_after_checkout_billing_form', 'add_vat_field_to_checkout' ); function add_vat_field_to_checkout() { woocommerce_form_field( 'vat', array( 'type' => 'text', 'required' => true, 'label' => 'VAT number', 'description' => 'Please enter your VAT number', ), $checkout->get_value( 'vat' ) ); }
And the result of the code:
woocommerce_form_field() select options
This function Use woocommerce_form_field() to add a custom select options field to the check-out page
add_action( 'woocommerce_before_order_notes', 'huyhoa_select_checkout_field' ); function huyhoa_select_checkout_field( $checkout ) { woocommerce_form_field( 'contactmethod', array( 'type' => 'select', 'required' => 'true', 'class' => array('contactmethod-class form-row-wide'), 'label' => __( 'How can we contact you?'), 'options' => array( // options for <select> or <input type="radio" /> '' => 'Please select', // empty values means that field is not selected 'via-email' => 'Via Email', // 'value'=>'Name' 'via-telephone' => 'Via Telephone', 'via-whatsup' => 'Via Whatsup') ), $checkout->get_value( 'contactmethod' )); }
Add custom CSS class to WooCommerce checkout fields
I would like to share the way I used to add a custom CSS class to WooCommerce checkout fields. I’m using Twitter Bootstrap 4.7 and I would like to be able to use their .form-control class. Here I will use the PHP foreach function to run through each form field and then add the value to the class
add_filter('woocommerce_checkout_fields', 'huyhoa_custom_css_class_ToCheckoutFields' ); function huyhoa_custom_css_class_ToCheckoutFields($fields) { foreach ($fields as &$fieldset) { foreach ($fieldset as &$field) { // if you want to add the form-group class around the label and the input $field['class'][] = 'form-group'; // add form-control to the actual input $field['input_class'][] = 'form-control'; } } return $fields; }
‘type’ => ‘hidden’ is not supported by woocommerce_form_field(). Therefore, we must use our own function to display and save the data of this hidden field when the customer submits the order.
The example below will save the IP address of the customer when submitting the order to the database along with the order data
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_hidden_field', 10, 1 ); function my_custom_checkout_hidden_field( $checkout ) { $user_ip = $_SERVER['REMOTE_ADDR']; // Output the hidden link echo '<div id="user_link_hidden_checkout_field"> <input type="hidden" class="input-hidden" name="user_ip" id="user_ip" value="' . $user_ip . '"> </div>'; }
Then you will need to save this hidden field in the order:
add_action( 'woocommerce_checkout_update_order_meta', 'save_custom_checkout_hidden_field', 10, 1 ); function save_custom_checkout_hidden_field( $order_id ) { if ( ! empty( $_POST['user_ip'] ) ) update_post_meta( $order_id, '_user_ip', sanitize_text_field( $_POST['user_ip'] ) ); }
Add a checkbox field to the checkout
The code below has the goal of adding a checkbox that says “Add me to your mailing list”. This functionality does work to provide a checkbox that is required to proceed.
// Add a checkbox field to the WooCommerce checkout page add_action( 'woocommerce_register_form', 'huyhoa_add_checkbox_to_checkout', 11 ); function huyhoa_add_checkbox_to_checkout() { woocommerce_form_field( 'receive_email', array( 'type' => 'checkbox', 'class' => array('form-row receive-email'), 'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'), 'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'), 'required' => true, 'label' => 'I want to receive email from Huy Hoa', )); } // Show error after clicking submit button if the user has not checked checkbox add_filter( 'woocommerce_registration_errors', 'hh_validate_receive_email', 10, 3 ); function hh_validate_receive_email( $errors, $username, $email ) { if ( ! is_checkout() ) { if ( ! (int) isset( $_POST['receive_email'] ) ) { $errors->add( 'receive_email_reg_error', __( 'You are not agree to receive email from us!', 'woocommerce' ) ); } } return $errors; }
If you want the Checkbox Checked by default, you can replace the functions below in the code above:
add_action( 'woocommerce_register_form', 'huyhoa_add_checkbox_to_checkout', 11 ); function huyhoa_add_checkbox_to_checkout() { $checked = $checkout->get_value( 'receive_email' ) ? $checkout->get_value( 'receive_email' ) : 1; echo '<div id="my-new-field"><h3>'.__('I want to receive email from Huy Hoa: ').'</h3>'; woocommerce_form_field( 'receive_email', array( 'type' => 'checkbox', 'class' => array('input-checkbox'), 'label' => __('I want to receive email from Huy Hoa.'), 'required' => true, ), $checked); echo '</div>'; }
Add a custom field to WooCommerce checkout page by use woocommerce_form_field() function
To add a custom field to the WooCommerce checkout page by using the woocommerce_form_field() function, you need to follow these steps:
First, you need to use the woocommerce_checkout_fields filter hook to add your custom field to the checkout fields array. You can choose which section to add your field to, such as billing, shipping, or order. You also need to specify the field parameters, such as type, label, placeholder, class, etc. For example, if you want to add a text field to the billing section, you can use this code:
add_filter( 'woocommerce_checkout_fields', 'custom_checkout_field' ); function custom_checkout_field( $fields ) { // Add a new text field to the billing section $fields['billing']['my_text_field'] = array( 'type' => 'text', 'label' => 'My Text Field', 'placeholder' => 'Enter some text', 'required' => true, 'class' => array('form-row-wide'), ); return $fields; }
Second, you need to use the woocommerce_form_field() function to display your custom field on the checkout page.
You can use the woocommerce_checkout_after_customer_details action hook to insert your field after the customer details section. You also need to pass the field key, parameters, and value to the function.
For example, if you want to display the text field that you added in the previous step, you can use this code:
add_action( 'woocommerce_checkout_after_customer_details', 'custom_checkout_field_display' ); function custom_checkout_field_display() { // Get the checkout object global $woocommerce; $checkout = $woocommerce->checkout(); // Display the text field using woocommerce_form_field() function woocommerce_form_field( 'my_text_field', $checkout->checkout_fields['billing']['my_text_field'], $checkout->get_value( 'my_text_field' ) ); }
Third, you need to save and validate your custom field data when the order is placed. You can use the woocommerce_checkout_process action hook to validate your field input and display an error message if it’s invalid.
You can also use the woocommerce_checkout_update_order_meta action hook to save your field data as order metadata.
For example, if you want to validate and save the text field that you added in the previous steps, you can use this code:
add_action( 'woocommerce_checkout_process', 'custom_checkout_field_process' ); function custom_checkout_field_process() { // Check if the text field is set and not empty if ( ! isset( $_POST['my_text_field'] ) || empty( $_POST['my_text_field'] ) ) { // Display an error message wc_add_notice( __( 'Please enter some text in My Text Field.' ), 'error' ); } } add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta' ); function custom_checkout_field_update_order_meta( $order_id ) { // Check if the text field is set and not empty if ( isset( $_POST['my_text_field'] ) && ! empty( $_POST['my_text_field'] ) ) { // Save the text field as order meta data update_post_meta( $order_id, '_my_text_field', sanitize_text_field( $_POST['my_text_field'] ) ); } }
Add an attribute to woocommerce_form_field
If you actually want to add an attribute to woocommerce_form_field then you can add the woocommerce_form_field_checkbox filter hook.
You just need to add this hook after the code you added the custom field
function filter_woocommerce_form_field_checkbox( $field, $key, $args, $value ) { // Based on key if ( $key == 'receive_email' ) { $field = str_replace( '<input', '<input required', $field ); } return $field; } add_filter( 'woocommerce_form_field_checkbox', 'filter_woocommerce_form_field_checkbox', 10, 4 );
As you can see, the example above will require the receive_email field to be required. However, in my opinion, the required parameter is a bit disappointing. You would always expect WooCommerce developers to at least implement both, must validate “ required ” both in frontend and backend. However, currently, if you want "required"
to a certain field, you need to build an accompanying function to validate it.
Set the default value of woocommerce_form_field
To add a default value arg to the checkout form fields, simply add ‘default’ => $value, to the array in the function. Eg:
woocommerce_form_field( 'how_old', array( 'type' => 'text', 'required' => 'true', 'default' => 25, // Default value show 25 'class' => array('howold-class form-row-wide'), 'label' => __('How old are you?'), ), $checkout->get_value( 'how_old' ));
Woocommerce_form_field radio
Add radio buttons before the order total in the WooCommerce Order review section. I figured out how to add custom radio buttons to the order review section. Here is the code:
woocommerce_form_field( 'delivery', array( 'type' => 'radio', 'class' => array( 'form-row-wide', 'update_totals_on_change' ), 'options' => array( '2.95' => 'Urgent delivery: €2.95', '0' => 'Normal delivery: 24 - 48 HOURS (free)', ), ), $chosen );
Woocommerce_form_field priority
To set priority for custom fields or reorder checkout fields, you must first create that field
woocommerce_form_field( 'vat', array( 'type' => 'text', 'required' => true, 'label' => 'VAT number', 'description' => 'Please enter your VAT number', ), $checkout->get_value( 'vat' ) );
You then rearrange the order of the fields this way:
$fields['billing_vat']['priority'] = 10;
The code above will move the position of the VAT field to the top right after the first name field
Woocommerce_form_field read-only
There are 2 ways to create a read-only field for Woocommerce Billing Fields or Woocommerce Shipping Fields
The first way is to use the Add an attribute to woocommerce_form_field as mentioned above to add the readonly="readonly"
attribute to it.
Method 2, use the code below:
add_filter( 'woocommerce_billing_fields', 'huyhoa_readonly_billing_account_fields', 25, 1 ); function huyhoa_readonly_billing_account_fields ( $billing_fields ) { // Only my account billing address for logged in users $readonly = ['readonly' => 'readonly']; $billing_fields['billing_first_name']['custom_attributes'] = $readonly; $billing_fields['billing_last_name']['custom_attributes'] = $readonly; $billing_fields['billing_email']['custom_attributes'] = $readonly; return $billing_fields; }
Note that it does not apply to live websites because the example above will make the 3 fields first_name / last_name / email read-only and cannot enter data.
Use woocommerce_form_field() for date and time fields
To use woocommerce_form_field() for date and time fields, you need to set the type parameter in the $args array of woocommerce_form_field()
function to ‘date
‘ or ‘datetime
‘. This will create an HTML5 date
or datetime
input field that allows the user to select a date or a date and time from a calendar.
For example, if you want to create a date field, you can use this code:
woocommerce_form_field( 'my_date_field', array( 'type' => 'date', 'label' => 'My Date Field', ), $value );
This will create a date field with the label “My Date Field” and a calendar icon.
If you want to create a datetime
field, you can use this code:
woocommerce_form_field( 'my_datetime_field', array( 'type' => 'datetime', 'label' => 'My Datetime Field', ), $value );
This will create a datetime
field with the label “My Datetime Field” and a calendar icon with a clock.
Validate woocommerce_form_field
To validate woocommerce_form_field(), you need to use the validate parameter in the $args array of the woocommerce_form_field() function. The value of the validate parameter should be an array of validation classes for the field wrapper. For example, validate-email will validate email addresses using JS.
For example, if you want to validate a text field as an email address, you can use this code:
woocommerce_form_field( 'my_email_field', array( 'type' => 'text', 'label' => 'My Email Field', 'validate' => array('email'), ), $value );
This will create a text field with the label “My Email Field” and the validation class “email”.
You can use the validate parameter for any supported field types, and you can also use multiple validation classes for a single field.
The article references some tutorials from WooCommerce Docs and Stack Overflow