I’m trying to calculate how many variations with unique parent-product id are inside an order.
For example this my order:
Product A: Size: Small, Color: Red
Product A: Size Medium, Color: Blue
Product B: Size: Small, Color: Yellow
Product B: Size: Large, Color Blue
I want to calculate how many unique products exist in the order (in this case 2, A & B), and how many variables exist in each unique product (in this case 2 each).
How can I do this?
I tried something with this code, but I got stuck…
$order_id = $order->get_id();
$order_number = $order->get_order_number();
$order_quantity = $order->get_item_count();
# Iterating through each order items (WC_Order_Item_Product objects in WC 3+)
foreach ( $order_id->get_items() as $item_id => $item_values ) {
// Product_id
$product_id = $item_values->get_product_id();
// For product variation type
if( $item_values->is_type('variation') ){
if( $item_values->get_variation_id() > 0 ){
for ($x = 0; $x < $item_values->get_variation_id(); $x++) {
}
// Get the instance of the parent variable product Object
$parent_product = wc_get_product( $item->get_product_id() );
2
Answers
maybe this code can help to you
output :
Let me know if you have any question 😉
When you have an order item that is a product variation the
WC_Order_Item_Product
methods:get_variation_id()
gives the variation ID, an integer always higher than zero.get_product_id()
gives the parent variable product IDTo get the product counts from your code as you would like, use something like:
Now if you want to count quantities you will use
WC_Order_Item_Product
methodget_quantity()
.Related: Get Order items and WC_Order_Item_Product in WooCommerce 3