首页 > 解决方案 > 通过用户 ID 在 WooCommerce 中获取单个客户的所有订单和订单数据

问题描述

我想在插件中获取当前用户下订单的所有订单金额和付款日期。

我正在使用此代码,它当前打印订单值:就像这个 150001000 一样,其中第一个订单是 0(从右开始),第二个是 100,第三个是 15000。我想要完成的是将订单金额和日期放入变量中。

$customer = wp_get_current_user();
// Get all customer orders
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key'    => '_customer_user',
'orderby' => 'date',
'order' => 'DESC',
'meta_value'  => get_current_user_id(),
'post_type'   => wc_get_order_types(),
'post_status' => array_keys( wc_get_order_statuses() ),  'post_status' 
=> array( 'wc-processing'),
) );


//echo count( $customer_orders );
foreach ( $customer_orders as $customer_order ) {
$orderq = wc_get_order( $customer_order );
$totalq = $orderq->get_total();
echo $totalq;       
} 

标签: phpwordpresswoocommerce

解决方案


我用这种方法解决了我的需求(wc_get_orders供应商推荐使用):

    public function get_sum_of_paid_orders( int $user_id ): int {

        $customer_orders = [];
        foreach ( wc_get_is_paid_statuses() as $paid_status ) {
            $customer_orders += wc_get_orders( [
                'type'        => 'shop_order',
                'limit'       => - 1,
                'customer_id' => $user_id,
                'status'      => $paid_status,
            ] );
        }

        $total = 0;
        foreach ( $customer_orders as $order ) {
            $total += $order->get_total();

            // your code is here
        }

        return $total;
    }

推荐阅读