WooCommerce:在新订单邮件通知中显示订单内商品分类数量
解决WooCommerce订单邮件显示订单内商品分类及对应数量的问题
原代码问题分析
你当前的代码存在两个核心问题:
- 使用
$term->count获取的是全站该分类下的总商品数,并非当前订单内的商品数量 - 直接在商品循环中输出分类,会导致同一分类重复出现(比如同分类下多个商品),且最后一行的赋值输出完全逻辑错误
正确实现代码
要实现订单内各分类的商品数量统计,需要先遍历订单商品并汇总分类数量,再统一输出:
// 初始化数组存储分类与对应数量 $category_counts = array(); // 遍历订单中的所有商品 foreach( $order->get_items() as $item ) { // 获取商品ID和购买数量 $product_id = $item->get_product_id(); $quantity = $item->get_quantity(); // 获取商品所属的分类 $terms = wp_get_post_terms( $product_id, 'product_cat' ); foreach( $terms as $term ) { $term_name = $term->name; // 累加分类数量:如果已存在则加当前商品数量,否则初始化为当前数量 if( isset( $category_counts[$term_name] ) ) { $category_counts[$term_name] += $quantity; } else { $category_counts[$term_name] = $quantity; } } } // 输出汇总后的分类与数量 if( !empty( $category_counts ) ) { echo '<ul>'; foreach( $category_counts as $cat_name => $count ) { echo '<li>' . esc_html( $cat_name ) . ' – ' . esc_html( $count ) . '</li>'; } echo '</ul>'; }
使用说明
- 直接修改邮件模板:将这段代码添加到WooCommerce的订单邮件模板文件中(比如
customer-new-order.php),放在订单商品列表之后等合适位置即可。 - 使用钩子(推荐):如果不想直接修改模板文件,可通过钩子注入代码,避免主题更新丢失修改:
add_action( 'woocommerce_email_order_details', 'display_order_category_counts', 20, 4 ); function display_order_category_counts( $order, $sent_to_admin, $plain_text, $email ) { // 仅在客户新订单邮件中显示,可根据需求调整邮件类型 if( $email->id == 'customer_new_order' ) { $category_counts = array(); foreach( $order->get_items() as $item ) { $product_id = $item->get_product_id(); $quantity = $item->get_quantity(); $terms = wp_get_post_terms( $product_id, 'product_cat' ); foreach( $terms as $term ) { $term_name = $term->name; if( isset( $category_counts[$term_name] ) ) { $category_counts[$term_name] += $quantity; } else { $category_counts[$term_name] = $quantity; } } } if( !empty( $category_counts ) ) { echo '<h3>商品分类汇总</h3>'; echo '<ul>'; foreach( $category_counts as $cat_name => $count ) { echo '<li>' . esc_html( $cat_name ) . ' – ' . esc_html( $count ) . '</li>'; } echo '</ul>'; } } }
这段代码会按你需要的格式输出每个分类及对应订单内的商品数量,同时处理了多分类商品、多数量购买的情况,避免重复统计。
内容的提问来源于stack exchange,提问作者Hugo27
相关产品推荐
相关产品推荐

