【问题标题】:How to get the total amount spent by a user (customer) in WooCommerce?如何获取用户(客户)在 WooCommerce 中花费的总金额?
【发布时间】:2020-12-11 11:56:38
【问题描述】:

使用以下简码,我试图获取用户的总支出金额,但它正在减慢页面加载速度(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;
}

【问题讨论】:

  • 您似乎想要检索特定用户的已完成订单的总金额,对吗?现在,您正在检索所有用户的所有订单。然后您尝试在foreach 循环中将订单对象添加到一起。这显然行不通。您需要:$total_amount += $order->get_total();(但也许这是您将代码复制到 SO 时的拼写错误?)

标签: php wordpress woocommerce shortcode user-data


【解决方案1】:

您可以通过这种方式简单地使用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 文件中。经过测试并且可以工作。

【讨论】:

    猜你喜欢
    • 2019-12-17
    • 1970-01-01
    • 2019-07-22
    • 2015-09-07
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    相关资源
    最近更新 更多