How to Add Custom Checkout Fields to WooCommerce Programmatically
In this tutorial, we’ll cover how to add custom fields to the WooCommerce checkout page. These fields are helpful when you need to gather extra information from your customers, such as delivery preferences or the type of address (home or office).
Adding New Custom Fields
To add custom fields, we’ll use the woocommerce_checkout_fields filter. This filter allows us to modify the default checkout fields and add new ones.
add_filter( 'woocommerce_checkout_fields', 'wk_add_custom_checkout_field' );
function wk_add_custom_checkout_field( $fields ) {
$fields['shipping']['address_type'] = array(
'label' => __( 'Address Type', 'example' ),
'type' => 'text',
'placeholder' => _x( 'Type', 'placeholder', 'example' ),
'required' => false,
'class' => array( 'address-type' ),
'clear' => true
);
return $fields;
}
function wk_add_custom_checkout_field( $fields ) {
$fields['shipping']['address_type'] = array(
'label' => __( 'Address Type', 'example' ),
'type' => 'text',
'placeholder' => _x( 'Type', 'placeholder', 'example' ),
'required' => false,
'class' => array( 'address-type' ),
'clear' => true
);
return $fields;
}
Saving New Custom Fields
To save the custom field data when an order is placed, use the woocommerce_checkout_update_order_meta action.
add_action( 'woocommerce_checkout_update_order_meta', 'wk_save_custom_field_data' );
function wk_save_custom_field_data( $order_id ) {
if ( ! empty( $_POST['address_type'] ) ) {
update_post_meta( $order_id, 'address_type', sanitize_text_field( $_POST['address_type'] ) );
}
}
function wk_save_custom_field_data( $order_id ) {
if ( ! empty( $_POST['address_type'] ) ) {
update_post_meta( $order_id, 'address_type', sanitize_text_field( $_POST['address_type'] ) );
}
}