How to get total sum of orders by a user in woocommerce?

Member

by shyann , in category: PHP CMS , 8 months ago

How to get total sum of orders by a user in woocommerce?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , 8 months ago

@shyann 

To get the total sum of orders by a user in WooCommerce, you can use the following code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
$user_id = get_current_user_id(); //Get current user id
$total_sum = 0; //Initialize total sum

//Get all orders of the user
$orders = wc_get_orders( array(
    'limit' => -1,
    'customer' => $user_id,
) );

//Loop through each order and sum the total
foreach( $orders as $order ){
    $total_sum += $order->get_total();
}

echo 'Total sum of orders for user with ID ' . $user_id . ' is ' . wc_price( $total_sum );


You can add this code snippet to your theme's functions.php file or create a custom plugin to use it. This code will calculate the total sum of all orders made by the current user and display it on the front end.