如何获取用户(客户)在 WooCommerce 中花费的总金额?

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

使用以下短代码,我试图获取用户总花费金额,但它会减慢页面加载速度(6 秒)。

是否可以优化此代码以缩短加载时间?

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;
}

您可以这样简单地使用 WC_Customer method get_total_spent()

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"]

代码进入您的活动子主题(活动主题)的 function.php 文件。已测试并有效。