php WooCommerce -在新订单电子邮件通知中显示产品类别计数

o4hqfura  于 2023-06-28  发布在  PHP
关注(0)|答案(2)|浏览(94)

我试图显示一个新订单中所有类别的简单列表,以及该类别中订单中的项目数量。因此,一些沿着:
喷雾罐- 3个附件- 2个标记- 5个等
这是我到目前为止尝试过的,但显然它只是显示了该类别中的产品总数,而不仅仅是与此订单有关。

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

}
fdx2calv

fdx2calv1#

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

测试和作品。

zf9nrax1

zf9nrax12#

这是最后的代码,我工作,如果有人需要它。

<ul class="count">
    <?php
    $category_count = [];
    foreach($order->get_items() as $item){
        $terms = wp_get_post_terms( $item->get_product_id(), 'product_cat' );
        foreach($terms as $term){
            if(isset($category_count[$term->name]) && !empty($category_count[$term->name])){
                $category_count[$term->name] += (int)$item->get_quantity();
            }else{
                $category_count[$term->name] = (int)$item->get_quantity();
            }
        }
    }
    foreach($category_count as $name => $count){
        echo '<li>'.$name.' - '.$count.'</li>';
    }
    ?>
    
<p>Total Products: <?php echo $items_count = count( $order->get_items() ); ?></p>
    
</ul>

相关问题