I am trying to create custom meta data in the wp_woocommerce_order_itemmeta table. But to create the data I want to store as meta data requires I know the product_id of the order item that is created at the Woocommerce hook woocommerce_checkout_create_order_line_item.
I have succeeded in creating a meta record with a value from a session variable but my code fails when I try to get the order item's product_id. I would greatly appreciate a solution for this.
So the following code works by creating a record in wp_woocommerce_order_itemmeta table with meta_key of "_raw_location_id'
add_action('woocommerce_checkout_create_order_line_item', 'raw_order_item_meta', 20, 2);
function raw_order_item_meta( $order ) {
$order->update_meta_data( '_raw_location_id', $_SESSION['location_id'] );
}
So then I "enhanced" the code to create one more record but with the meta_key value of $product_id. In adding the code I thought necessary the checkout does not complete so I never get to the thank you page. The checkout page is re-displayed with no changes in the database. I did meticulous testing by adding one line of code at a time. I have number the lines of code below for easy reference.
I found that adding line "3" causes the error. So I have not been able to verify if lines 4 & 5 work or not and I took the code from another post so I can't even say I understand the syntax of line 5 I am just hoping it works as advertised. I think my first obstacle is line 3. Why is this not working? I just want to know what the product_id is of the order item being processed.
- add_action('woocommerce_checkout_create_order_line_item', 'raw_order_item_meta', 20, 2);
function raw_order_item_meta( $order ) {
$items = $order->get_items();
- foreach ( $items as $item_id => $item ) {
$product_id = $item->get_variation_id() ? $item->get_variation_id() : $item->get_product_id();
$order->update_meta_data( '_raw_location_id', $_SESSION['location_id'] );
$order->update_meta_data( '_raw_wc_product', $product_id );
}
- }