WooCommerce get_sku(); on products variations in order
On WooCommerce 3.x this line throws a fatal error:
$product = new WC_Product($item['variation_id']);
Uncaught exception 'Exception' with message 'Invalid Product'.
You can do this:
$sku = get_post_meta( $item['variation_id'], '_sku', true );
Talk about tunnel vision..
$product_variation_id = $item['variation_id'];
$product = new WC_Product($item['product_id']);
Solution was switching 'product_id' for my already in place 'variation_id'
$product = new WC_Product($item['variation_id']);
Voila, problem solved !
Working example
To get the expected output on $sku
i did go for this solution
// Get order data
$order = new WC_Order($order_id);
$items = $order->get_items();
// Loop through ordered items
foreach ($items as $item) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_qty = $item['qty'];
$product_variation_id = $item['variation_id'];
// Check if product has variation.
if ($product_variation_id) {
$product = new WC_Product($item['variation_id']);
} else {
$product = new WC_Product($item['product_id']);
}
// Get SKU
$sku = $product->get_sku();
}