I'm trying to display a simple list of all the categories within a new order that comes through, and the number of items in the order within that category. So something along the lines of:
Spray Cans – 3 Accessories – 2 Markers – 5 etc
This is what I've tried so far but obviously it just shows the total of products in the category and not just relating to this order.
foreach( $order->get_items() as $items ) {
$terms = wp_get_post_terms( $items->get_product_id(), 'product_cat' );
foreach( $terms as $term ) {
echo '<li>';
echo $term->name;
echo ' - ';
echo $term->count;
echo '</li>';
echo $term = count( $order->get_items() );
}
}
The following will list the product categories within the WC Order with the count for each of them and at the end you will have the count of order items:
$items = $order->get_items();// Get Order Items
$terms = $term_ids = array(); // Initializing
// Loop thriugh order items
foreach( $items as $item ) {
// Get the product categoory terms (array of WP_Term oblects)
$item_terms = wp_get_post_terms( $item->get_product_id(), 'product_cat' );
// Loop through the product category terms
foreach( $item_terms as $term ) {
$term_ids[] = $term->term_id; // add the term ID in an array
$terms[ $term->term_id ] = $term->name; // array of term ids / term names pairs
}
}
// Get an array with the count by term Id
$terms_count = array_count_values( $term_ids );
// Formatting for output
$html = '<ul class="order-terms-count">';
// loop through the terms count (array)
foreach( $terms_count as $term_id => $count ) {
// Format the term name with the count
$html .= '<li>' . $terms[$term_id] . ' - ' . $count . '</li>';
}
// output
echo '</ul>' . $html . '<p>Order items - ' . count( $items ) . '</p>';
Tested and works.