下面将列出WC订单中的产品类别以及每个类别的计数,最后您将获得订单项目的计数:
$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>';
经过测试,效果良好.