Reputation: 21
I'm creating a Woocommerce webshop for a client who is selling different types of breakfasts. Each breakfast has several variations based on the amount of persons.
For example:
Breakfast x (product)
- 1 person (variation)
- 2 persons (variation)
- 3 persons (variation)
- 4 persons (variation)
Each variation contains (different) meta data.
Basically the meta data contains the articles needed to create a breakfast and needs to be added to the order line items in woocommerce when an order is created. The composition of the meta data is different for each variation.
Now I'm able to add meta data to the order item, but somehow meta data gets mixed up when adding two or more products.
Below is my code and output in Woocommerce.
When I use the function just to print the variation meta data instead of adding it to the woocommerce order, I can see that the meta data is correct and the most inner for loop is executed one variation after another. I don't know if wc_add_order_item_meta is causing an issue or maybe the hook I'm calling.
function oc_line_item_metadata( $item_id, $item, $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ($items as $item) {
$variation_id = $item['variation_id'];
$product_variation = new WC_Product_Variation( $variation_id );
$meta_data = $product_variation->get_meta_data();
for ($i=0; $i < count($meta_data); $i++) {
$article = ($meta_data[$i]->get_data());
$article_id = $article['id'];
$article_key = $article['key'];
$article_value = $article['value'];
wc_add_order_item_meta( $item_id, $article_key, $article_value );
}
}
}
add_action( 'woocommerce_new_order_item', 'oc_line_item_metadata', 10, 3 );
You can find the output via this link:
https://image.ibb.co/mtsnrb/order.png
Upvotes: 1
Views: 1552
Reputation: 21
Yesterday I found some more information that helped me solve the issue. It seems I'm not using the correct method to get the order_id and variation_id.
Below the correct code that solved my issue:
function oc_line_item_metadata( $item_id, $item, $order_id ) {
$order = wc_get_order( $order_id );
foreach ($order->get_items() as $item_id => $item_obj) {
$variation_id = $item_obj->get_variation_id();
}
$product_variation = new WC_Product_Variation( $variation_id );
$meta_data = $product_variation->get_meta_data();
for ($i=0; $i < count($meta_data); $i++) {
$article = ($meta_data[$i]->get_data());
$article_id = $article['id'];
$article_key = $article['key'];
$article_value = $article['value'];
wc_add_order_item_meta( $item_id, $article_key, $article_value );
}
}
Upvotes: 1