How to get the total amount spent by a user (customer) in WooCommerce?

Viewed 1722

With the following shortcode I am trying to get user total spent amount, but it is slowing page load (6 seconds).

Is it possible to optimize this code to shorten the loading time?

add_shortcode('woo-total-completed', 'get_user_total_completed');

function get_user_total_completed() {
    $total_amount = 0; // Init

        $total_completed_orders = wc_get_orders( array(
            'limit' => -1,
            'status' => 'wc-completed',
        ) );

        foreach( $total_completed_orders as $order) {
            $total_amount += $order;
        }
    return $total_amount;
}
1 Answers

You can simply use WC_Customer method get_total_spent() this way:

add_shortcode('user_total_spent', 'get_user_total_spent');

function get_user_total_spent( $atts ) {
    extract( shortcode_atts( array(
        'user_id' => get_current_user_id(),
    ), $atts, 'user_total_spent' ) );

    if( $user_id > 0 ) {
        $customer = new WC_Customer( $user_id ); // Get WC_Customer Object

        $total_spent = $customer->get_total_spent(); // Get total spent amount

        return wc_price( $total_spent ); // return formatted total spent amount
    }
}

// USAGE: [user_total_spent] or [user_total_spent user_id="118"]

Code goes in function.php file of your active child theme (active theme). Tested and works.

Related