You are currently viewing How to add custom field in woocommerce checkout page? 1 Quick solution

How to add custom field in woocommerce checkout page? 1 Quick solution

To add custom field in woocommerce checkout page, here is some sample code that you can use to modify the billing details fields on the WooCommerce checkout page:

Custom code to add custom field in woocommerce checkout page

// Add a custom billing field
add_action( 'woocommerce_before_checkout_billing_form', 'custom_checkout_field' );
function custom_checkout_field( $checkout ) {
    echo '<div id="custom_checkout_field"><h2>' . __('My Custom Field') . '</h2>';
    woocommerce_form_field( 'custom_field_name', array(
        'type'          => 'text',
        'class'         => array('custom-field-class form-row-wide'),
        'label'         => __('Custom Field'),
        'placeholder'   => __('Enter your custom field'),
        ), $checkout->get_value( 'custom_field_name' ));
    echo '</div>';
}

// Process the custom field on checkout
add_action('woocommerce_checkout_process', 'custom_field_process');
function custom_field_process() {
    // Check if set, if its not set add an error.
    if ( ! $_POST['custom_field_name'] )
        wc_add_notice( __( 'Please enter a value for the custom field.' ), 'error' );
}

// Update the order meta with field value
add_action( 'woocommerce_checkout_update_order_meta', 'custom_field_update_order_meta' );
function custom_field_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['custom_field_name'] ) ) {
        update_post_meta( $order_id, 'Custom Field', sanitize_text_field( $_POST['custom_field_name'] ) );
    }
}

// Display field value on the order edit page
add_action( 'woocommerce_admin_order_data_after_billing_address', 'custom_field_display_admin_order_meta', 10, 1 );
function custom_field_display_admin_order_meta($order){
    echo '<p><strong>'.__('Custom Field').':</strong> ' . get_post_meta( $order->get_id(), 'Custom Field', true ) . '</p>';
}

This code will add a new text field to the billing section of the checkout page, process the field value when the order is placed, and display the field value on the order edit page in the woocommerce order page. You can modify the code to change the field type, label, placeholder, other settings as needed.

Note: This code should be placed in the function.php file of your active theme, or you can use the code snippets plugin to add a custom field in woocommerce checkout page.

Are you looking for to customize your WordPress website? Check here

Join us of Facebook

Leave a Reply