'Sum the quantities of products ordered by product categories from a WooCommerce order
I'm really stuck on this and I'd really appreciate any help with this.
The goal is to count the number of items in each category on a Woocommerce order so that each section can be headed by the category name and number of products. eg:
Burgers x 5
Below this will then be a list of all the burgers on that order.
Now I thought I had this working with this code:
$categories = [];
foreach ($order->get_items() as $item) {
$product_id = $item['product_id'];
$meta = $item['item_meta'];
$meta = array_filter($meta, function ($key) {
return !in_array($key, Order::getHiddenKeys());
}, ARRAY_FILTER_USE_KEY);
$terms = get_the_terms($product_id, 'product_cat');
$cat_id = $terms[0]->term_id;
$categories[$cat_id][] = $item;
$cat_name = $terms[0]->name;
}
foreach($categories as $category => $items){
?>
<tr>
<td colspan="3">
<h4>
<?php
if( $term = get_term_by( 'id', $category, 'product_cat' ) ){
echo $term->name.' ('.$term->count.')';
echo " × ";
echo count($items);
}
?>
</h4>
</td>
</tr>
<?php
But I've realised that this simply counts the number of products that have been ordered in that category, not the quantity. So if one of there was more than one of the same product, it would not count it. So for example, if the category contained these three items:
Cheeseburger x 2
Hamburger x 1
Would return two instead of three.
I've been looking through the categories and terms arrays but can't seem to find anything that's going to work. I'm sure I'm missing something but I'm just at a loss right now.
Can anyone point me in the right direction please?
(Also, if it's of any use, this is an indirect follow on from a previous question Filtering the Woocommerce $order items By Category (Term))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
