How to Add Custom Checkout Field in the Address Block

How to Add Custom Checkout Field in the Address Block

Getting your Trinity Audio player ready...

3. Process Custom Field Data in Backend

Once the custom field value is submitted, you need to handle it in the backend. Hook into WooCommerce’s checkout process using the appropriate WooCommerce filters to validate and save the field value.

Example: Processing the Custom Field in PHP

In your main plugin file or functions.php, use WooCommerce’s hooks to handle the custom field:

// Validate the custom field
function my_custom_checkout_field_process() {
    if ( isset( $_POST['custom_field'] ) && empty( $_POST['custom_field'] ) ) {
        wc_add_notice( __( 'Please fill in your custom field.' ), 'error' );
    }
}
add_action( 'woocommerce_checkout_process', 'my_custom_checkout_field_process' );

// Save the custom field to the order meta
function my_custom_checkout_field_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['custom_field'] ) ) {
        update_post_meta( $order_id, '_custom_field', sanitize_text_field( $_POST['custom_field'] ) );
    }
}
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );

// Display custom field in the order admin
function my_custom_checkout_field_display_admin_order_meta( $order ) {
    $custom_field = get_post_meta( $order->get_id(), '_custom_field', true );
    if ( $custom_field ) {
        echo '<p><strong>' . __( 'Custom Field:' ) . '</strong> ' . esc_html( $custom_field ) . '</p>';
    }
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );

Similar Posts

Leave a Reply