I need add a custom data on Processing order email, but the data always update after the email is sent, like this:
Order status change ==> Send email ==> Insert data on custom table (plugin)
What I need instead is:
Order status change ==> Insert data on custom table (plugin) ==> Send email.
I have checked and this is done with the following hooked function:
add_action('woocommerce_order_status_changed', 'fun_order_status_changed', 10, 4);
function fun_order_status_changed($order_id, $from_status, $to_status, $order){
// Some code
// Then insert to database
}
How could I do or what files can I need to modify so that first the insert is saved in the database and then the e-mail is sent?
EDIT 1
I put deliberately a var_dump and first execute the mail templeate
2
Answers
You can try to use
woocommerce_order_status_pending_to_processing_notification
action hook with alower priority
, for example 5. So that it will get processed before the mail is sent.If you want to add a custom field to the order meta data, send the value of this field with the order confirmation mail, and additionally display it in the order detail and edit screen in the backend, you can use the follwing code. There are multiple steps to be done.
'woocommerce_after_checkout_billing_form'
. (just a sidenote: If you have other purposes, you can also i.e. use a hidden field and a given value)'woocommerce_checkout_update_order_meta'
'woocommerce_email_order_meta_keys'
'woocommerce_order_details_after_order_table'
and for the order edit screen'woocommerce_admin_order_data_after_billing_address'
This will place it below the billing address. Notice: The value will not show up (but still be saved in database), if the order is made within the backend, only works for orders placed in the frontend (Would go beyond the scope now).In my code example, I did this steps to add a VAT ID field which is important in europe for business to business transactions. The VAT ID is also added to the emails and backend screens.
You can adjust the names (vat_number, or the "mrank" prefixes) to your needs, but remember to keep it consistent.