Custom Woocommerce Checkout Fields Without A Plugin

Checkout Purchase Online Shopping Concept

In this article, we’ll show you how to use custom functions to add additional fields to the WooCommerce checkout page, and how to map those fields to the WooCommerce user without the need for an additional plugin. This can be a useful way to collect additional information from customers during the checkout process, and can be used in a variety of ways, such as in custom reports or email notifications.

 

Before starting this I highly recommend taking a backup of your WordPress site, and if you are not already using a child theme it might be time to set one up.

				
					add_action( 'woocommerce_before_order_notes', 'add_custom_checkout_fields' );

function add_custom_checkout_fields( $checkout ) {
    // Add a custom text field
    woocommerce_form_field( 'custom_text_field', array(
        'type'          => 'text',
        'class'         => array('custom-text-field form-row-wide'),
        'label'         => __('Custom Text Field'),
        'placeholder'   => __('Enter your custom text'),
    ), $checkout->get_value( 'custom_text_field' ));

    // Add a custom select field
    woocommerce_form_field( 'custom_select_field', array(
        'type'          => 'select',
        'class'         => array('custom-select-field form-row-wide'),
        'label'         => __('Custom Select Field'),
        'options'       => array(
            '' => __('Select an option'),
            'option1' => __('Option 1'),
            'option2' => __('Option 2'),
            'option3' => __('Option 3'),
        ),
    ), $checkout->get_value( 'custom_select_field' ));
}

				
			

To use this function, simply add it to your WordPress theme’s functions.php file. This will ensure that the custom fields are displayed on the checkout page. You can then customize the fields as needed to meet your specific requirements.



Now lets save those values and map them to the users in WordPress / Woocommerce 

				
					add_action( 'woocommerce_checkout_update_user_meta', 'save_custom_checkout_fields' );

function save_custom_checkout_fields( $user_id ) {
    // Save the custom text field
    if ( isset( $_POST['custom_text_field'] ) ) {
        update_user_meta( $user_id, 'custom_text_field', sanitize_text_field( $_POST['custom_text_field'] ) );
    }

    // Save the custom select field
    if ( isset( $_POST['custom_select_field'] ) ) {
        update_user_meta( $user_id, 'custom_select_field', sanitize_text_field( $_POST['custom_select_field'] ) );
    }
}

				
			

This function will save the values entered into the custom fields to the user’s meta data. This will allow you to access the field values for use in other areas of your WordPress site, such as in custom reports or email notifications.