WooCommerce checkout page is modular. We can easily add new checkout field or edit existing fields or remove existing fields.
There are two ways to add custom field in checkout page. They are: using woocommerce_checkout_fields
filter and adding a custom field on certain locations.
woocommerce_checkout_fields
makes it very easy to add new field, as it handles all validation and form data storing to database. In this article we will learn how to add custom checkout field on WooCommerce using woocommerce_checkout_fields
filter.
Create new checkout field
First we will add the new field.
function careless_woo_custom_billing_field( $fields ) {
//add field - select/dropdown
$fields['billing']['billing_about'] = array(
'label' => 'About you...',
'required' => true,
'clear' => true,
'type' => 'select',
'class' => array( 'form-row-wide' ),
'priority' => 25,//so it sits before billing company name
);
//select - options
$fields['billing']['billing_about']['options'] = array(
'A tradesperson' => 'A tradesperson',
'A shop fitter' => 'A shop fitter',
'An architect' => 'An architect',
'A homeowner' => 'A homeowner',
'Other' => 'Other',
);
return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'careless_woo_custom_billing_field' );
With above code, we are adding a new select/dropdown field to checkout page. We have used priority 25 (on line 9), so that it sits before billing company name.
Show new checkout field in admin order edit screen
Now we will show this field in admin order view/edit screen.
function careless_woo_custom_billing_field_display_admin_order_meta( $order ){
echo '<p><strong>'.__('About you:').':</strong> ' . get_post_meta( $order->get_id(), '_billing_about', true ) . '</p>';
}
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'careless_woo_custom_billing_field_display_admin_order_meta', 10, 1 );
Code goes in the functions.php
file of your active theme.