I’m creating a custom plugin for my website.
In some part of this plugin I need to store extra meta in wp_postmeta
for each orders.
I added this in my plugin’s class:
add_action ('woocommerce_before_checkout_process', array( &$this, 'add_item_meta', 10, 2) );
And this is add_item_meta()
function:
function add_item_meta( $item_id, $values ) {
wc_add_order_item_meta($item_id, '_has_event', 'yes' );
}
This function is not complete, but nothing happens with this codes; I think I need to use another hook but I can’t find a proper one.
Does anyone know anything about this?
I also have another problem with $item_id
: this is woocommerce global variable but I can’t see it in my plugin!
I mean I don’t have access to this variable from my plugin or something like this!
The 2018 way:
Built on Guido W.P. answer you can use instead
woocommerce_checkout_create_order
action hook ina more lighter and effective version code (using WC 3+ CRUD methods):
Code goes in function.php file of your active child theme (or active theme).
Tested and works in WooCommerce 3+ (only).
SOME EXPLANATIONS:
The
woocommerce_checkout_create_order
action hook is just one step before saving the order data. See below in an extract of theWC_Checkout
create_order()
method (with both hooks):Building on Mo Saeedi answer, I believe this snippet is more in line with the new CRUD approach introduced by WooCommerce 3.0:
See also this threads on the WordPress forums:
answer is:
I should use
woocommerce_checkout_update_order_meta
for add_action and also i should simply useupdate_post_meta()
to add extra meta to my orderThe 2016 way:
$order_id
is the id of the order, which is stored as a custom post type$posted
is all the data from$_POST