I’m doing something similar. I started off with an approach similar to yours, but made it slightly faster by directly using WC API Query instead of WP Query.
I am still looking for a way to query the variation from all orders…
//get number of orders per variation_id
function getOrdersfromVariation($variation_id){
$numberOfOrders = 0;
ip_write_log("getOrdersfromVariation varid: $variation_id");
// rewrite with wc_get_orders
$args = array(
'status' => array( 'processing', 'completed'),
'limit' => -1,
);
$orders = wc_get_orders( $args );
if(isset($orders)){
//TODO: Get order count - $total_orders = $orders->total;
foreach ($orders as $order){
foreach ($order->get_items() as $key => $lineItem) {
$item_data = $lineItem->get_data();
if ($item_data['variation_id'] == $variation_id) {
$numberOfOrders++;
}
}
}
if(isset($numberOfOrders)){
return $numberOfOrders;
}
}
return;
}