WooCommerce:如何计算和列出状态为“暂停”的每个订单的总重量,并计算所有订单的总金额和总重量

问题描述

一段时间以来,我一直在思考和研究如何在没有直接 sql 查询的情况下并按照良好的 woocommerce 实践来实现这一点。

我从去年开始就掌握了一些 WooCommerce、PHPsql、HTML、CSS 知识。

我希望我的代码对那些在网上徒劳地搜索这样做的人有用。

请告诉我您的改进建议。

解决方法

function kg_total(){
    
    ?>
    <div class="wrap">
        <h2>Total weight (kg):</h2>
    </div>
    <?php   
    
    $order_weight = 0;
    $orders_weight = 0;
    
    $on_hold_orders = wc_get_orders( array(
    'limit' => -1,// 'customer_id' => $user->ID,'post_type' => 'shop_order','status'    => 'on-hold',) );
    
    ?>
    <table class="table">
    <thead>
        <tr>
            <th data-sort="int">order_ID</th>
            <th data-sort="string">order_weight</th>
            <th data-sort="string">last name</th>
            <th data-sort="string">first name</th>
        </tr>
    </thead>
    
    <tbody> 
    <?php
    
    foreach( $on_hold_orders as $order) {
        // Gesamt €
        $total_amount += $order->get_total();
        
        foreach( $order->get_items() as $item ) {
        // Gesamt kg per order
        if ( $item['product_id'] > 0 ) {
            $_product = $item->get_product();
                if ( ! $_product->is_virtual() ) {
                    $order_weight += $_product->get_weight() * $item['qty'];

                }
            }
        }
        $orders_weight = $orders_weight + $order_weight;
        
        echo '<td style="color: #0000aa;"><b>' . $order->get_id() . '</b></td>';
        echo '<td style="text-align:right;"><b>' . $order_weight . ' kg - </b></td>';
        echo '<td>' . '<b>' . strtoupper( $order->get_billing_last_name() ) . '</b>' . '</td>';
        echo '<td>' . $order->get_billing_first_name() . '</td>';
        echo '</tr>';
                
        $order_weight = 0;
        
    }
    echo '</tbody>';
    
    echo '<br>';
    echo '<p style="color: #0000aa; font-size: 20px;"><b>Total amount (on hold): ' . $total_amount . ' €</b></p>';
    echo '<p style="color: #aa0000; font-size: 20px;"><b>Total weight (on hold): ' . $orders_weight . ' kg</b></p>';
        
}