我正在try 显示一个新订单中所有类别的简单列表,以及该类别中订单中的项目数量.因此,大致是这样的:

喷雾罐-3 配件-2 标记-5 等

这就是我到目前为止try 过的,但显然它只显示了类别中的产品总数,而不仅仅是与此订单相关.

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() );
} 

}

推荐答案

下面将列出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>';

经过测试,效果良好.

Php相关问答推荐

如何发送woocommerce订单跟踪码与短信

在函数内部获取一致的单选按钮值以更新WordPress用户数据

向在添加到购物车上动态创建的WooCommerce产品添加发货类别

无法在WooCommerce中发送客户笔记邮箱通知

如何在Foreach语句中使用php和li按降序排序?

由于某种原因,FILE_GET_CONTENTS从一天到另一天停止工作,并在PHP 7.2.34中返回一条&http/1.1 406不能接受&的错误

在WooCommerce中设置带有国家/地区和年份前缀的顺序序号

Symfony 6.2 IsGraned具有多个角色

在laravel 9或10 php中向中间件响应添加自定义数据

Laravel服务Provider 没有向服务类注入价值

无额外字段的Laravel同步

文件::Files()响应返回空对象数组

隐藏WooCommerce管理子菜单;主页;来自store 经理

execute_query 和prepare+execute 有什么区别?

多个产品类别 Select 自定义 WooCommerce 插件设置页面

woocommerce checkout 页面上的自定义字段

Google Drive API:为什么使用服务帐户在下载文件时会将我带到 Google Drive 登录窗口?

PHP 合并/合并多维数组

PHP 将数组值插入到 csv 列

为什么在 phpunit 的开头测试 PHP_VERSION?