0

I am trying to get the query for highest customers' total number of orders via the WC get orders but do not seem to be able to get that information via wc_get_orders. Hoping someone can guide me out. Here's my attempt in the snippet but it just returns the total number of sales by each customer without sorting from Highest to Lowest.

$i = 0;

    foreach ($customer_ids as $customer_id) :
        $customer = new WP_User($customer_id);


        $args = array(
          'status' => 'completed',
          'customer_id' => $customer_id,
          'limit' => '-1',
        );

        $orders      = wc_get_orders( $args );

        update_option( '_gpdebug_contributor_list_d',$orders );

        ?>
        <?php
        $i++;
        if (!empty($orders)) : ?>
        <tr>
            <td><?php echo $i; ?></td>
            <td><?php $bp_name = bp_core_get_userlink( $customer_id ); ?><?php echo get_avatar($customer_id, 30) . $bp_name;
            if ( $i == 1 ) {
              echo '<span class="ion-trophy gold"></span>';
            } elseif ( $i == 2 ) {
              echo '<span class="ion-trophy silver"></span>';
            } elseif ( $i == 3 ) {
              echo '<span class="ion-trophy bronze"></span>';
            }
            ?></td>
            <td style="text-align: right;">
              <?php

                $total = 0;

                foreach ( $orders as $order ) {
                  $customer_order = wc_get_order( $order );
                  $total += $customer_order->get_total();
                }
                echo $total;

Thanks in advance.

Calvin Seng
  • 193
  • 1
  • 19

1 Answers1

1

I understand that you already get totals of orders for each customer. This will require some changes in your code but I think you can easily modify it.

Create an array,

$customer_totals = array();

Then insert each customer id as key and total of orders for this customer as value (*),

$temp_arr = array($customer_id => $total);
$customer_totals =array_merge($customer_totals , $temp_arr);

After insertion of all customer ids and totals, sort the final array in descending order (**),

arsort($customer_totals);

Now you can display the totals as you wish. I hope this helps. Please inform me if you have any problems by updating your code.

*https://stackoverflow.com/a/9735696

**https://www.w3schools.com/php/func_array_arsort.asp

MrEbabi
  • 740
  • 5
  • 16