In my WooCommerce plugin I’m using woocommerce_checkout_update_order_meta
hook to handle custom checkout fields I added.
First I add action:
add_action('woocommerce_checkout_update_order_meta', __NAMESPACE__ . 'my_update_order_meta');
here below the function:
`function my_update_order_meta()
{
$order = new WC_Order();
$billing_fields = ['billing_fiscalcode', 'billing_vatcode'];
foreach ($billing_fields as $field) {
if (!empty(sanitize_text_field($_POST[$field]))) {
$order->update_meta_data($field, sanitize_text_field($_POST[$field]));
}
}
}`
When I try to place an order in my shop I get a checkout error. Diving a little in the code I got that I’m not placing the order because its id is 0. Any idea about a solution?
I tried to use wc_create_order() as suggested here, I’m still failing
2
Answers
At last I found a solution. I used
woocommerce_checkout_create_order
as suggested by LoicTheAztec (thanks for help!), then I edited the function like this:The main mistake is that you forgot the hook argument
$order_id
in the function and then you should replace:with:
to make it work, at the end, before the last closing bracket, you need to add:
But, since WooCommerce 3, use instead
woocommerce_checkout_create_order
hook as follows:Code goes in functions.php file of your child theme (or in a plugin). It should work.
For a plugin, you should need to replace:
with:
Notes:
woocommerce_checkout_create_order
hook, the function doesn’t need$order->save();
as it is included just after the hook.add_meta_data()
method thanupdate_meta_data()
as you are adding metadata (not updating it).