In WooCommerce, I would like to add a new custom field to order details. I now that I can use use the code below to create a new custom field ‘referenceNumber’ and adds in it "ordercreated" value:
update_post_meta($order_id, 'referenceNumber', 'ordercreated']);
What I would like is to make that through checkout once an order is placed.
But it doesn’t work it doesn’t add a new custom field to order details page and don’t add the value ‘ordercreated’, as you can see in this screenshot:
So the question is how to add a custom field when an order is placed in WooCommerce?
2
Answers
Hi i had a similar requirement few days ago, as i needed to add new field at checkout. Following article helped me. You can check it too. Here is the link. Basically you will have a write a function which will use woo commerce hook "woocommerce_default_address_fields"
https://wisdmlabs.com/blog/add-custom-fields-woocommerce-checkout-page/
To add a custom field to an order you can use:
WordPress
update_post_meta()
function (from an order id):WooCommerce
WC_Data
update_meta_data()
method (from the order object or the order id):Where
referenceNumber
is the meta key andordercreated
is the meta value. Both works.Now to add a custom field to an order when customer place an order, you can use:
woocommerce_checkout_create_order
action hook (before order data is saved – used to adjust order data before it’s saved):woocommerce_checkout_update_order_meta
action hook (order already exist – used to add custom meta data):woocommerce_checkout_order_created
action hook (order already exist – to trigger an action or also to add custom meta data):Or:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.