Add Custom Form Field on WooCommerce Checkout Page

Sometimes we want to add some other/extra information of the user on checkout. For example, we want to add a privacy policy checkbox or want to add a dropdown to select specific information etc.

So for this woocommerce provide us another useful filter which allows us to add the custom form field on the checkout page.

Logically we’ll have to use one filter and one action for this process:

add_filter( ‘woocommerce_checkout_fields’ , ‘custom_drop_down’);

This filter will display the customs form field on the checkout page.

This action will save the custom field data in the database.

How to use the filter ?

add_filter( 'woocommerce_checkout_fields' , 'custom_drop_down');

function custom_drop_down( $fields ) {

$fields['billing']['custom_drop_down'] = array(

'type' => 'select',
'options' => array(
'1' => 'Yes',
'0' => 'No',

),

'label' => __('Custom Dropdown', 'woocommerce'),
'required' => false,
'class' => array('custom_dropdown'),
'clear' => true

);

return $fields;

}

woocommerce_checkout_fields’ filter returns a parameter $fields which contain all the checkout page fields.

$fields is an array so we add new custom field value in this array and pass the args in this.

type => it define the field type e.g. text,select,text area etc.
options => it is used for select type only.
label => if define the field label.
required => it defines the field required a condition.
class => if define the field classes.

How to use action to store the custom field data ?


add_action( 'woocommerce_checkout_update_order_meta', 'custom_update_order_meta' );
function custom_update_order_meta( $order_id ) {

if ( $_POST[ ‘custom_dropdown’ ] )
update_post_meta( $order_id, 'custom_dropdown', esc_attr( $_POST[ 'custom_dropdown' ] ) );

}

as you can see the code. in that function, we’re checking the custom_dropdown data exist in post data or not ? if it exists then we update the post meta and store the custom field data in post meta table.

Thanks for reading.

Advertisements