5

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;
}
Jesse Nickles
  • 1,435
  • 1
  • 17
  • 25
  • It looks like you want to retrieve the total amount for completed orders for a specific user, correct? Right now you are retrieving all orders for all users. And you try to add order objects together in your `foreach` loop. Which obviously won't work. You need: `$total_amount += $order->get_total();` (But maybe this was a typo when you copied your code to SO?) – Terminator-Barbapapa Aug 22 '20 at 09:07

1 Answers1

3

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399