如何在woocommerce中获得用户的订单总和?

Vij*_*Lal 4 wordpress woocommerce

我在主题中使用 woocommerce 插件。我想要一个功能,我需要检查客户下订单的总和。在此基础上,我将为他们提供优惠券折扣。优惠券部分很清楚。但是我无法获得用户所做的所有订单的总和。

我的计划是:如果用户购买超过 300 美元,我们将向他提供优惠券。为此,我正在使用此操作。但是对于用户订单总和的查询表单数据库有困难。

function so_27969258_track_orders_per_customer($order_id){


    $order = new WC_Order( $order_id );
    $myuser_id = (int)$order->user_id;
    $user_info = get_userdata($myuser_id);
    $items = $order->get_items();
    foreach ($items as $item) {

    }
    return $order_id;

}
add_action( 'woocommerce_payment_complete', 'so_27969258_track_orders_per_customer' );
Run Code Online (Sandbox Code Playgroud)

我也试图通过我从 woocommerce/myaccount 文件夹中的 my-orders.php 获得的用户 ID 获取订单。我试图在 function.php 中运行此代码但返回空数组。

$customer_orders = get_posts( apply_filters( 'woocommerce_my_account_my_orders_query', array(
    'numberposts' => $order_count,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(),
    'post_type'   => wc_get_order_types( 'view-orders' ),
    'post_status' => array_keys( wc_get_order_statuses() )
) ) );


var_dump($customer_orders);
if ( $customer_orders ) : 


    foreach ( $customer_orders as $customer_order ) {
                $order = wc_get_order( $customer_order );
                $order->populate( $customer_order );
                $item_count = $order->get_item_count();

                 echo $order->get_order_number(); 
                 echo wc_get_order_status_name( $order->get_status() );
                 echo sprintf( _n( '%s for %s item', '%s for %s items', $item_count, 'woocommerce' ), $order->get_formatted_order_total(), $item_count );

            }



 endif;
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我这段代码如何在 function.php 中工作。我知道我错过了很多东西。请建议。

Meh*_*ran 6

您可以使用以下函数获取用户已完成订单的总和

public function get_customer_total_order() {
    $customer_orders = get_posts( array(
        'numberposts' => - 1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(),
        'post_type'   => array( 'shop_order' ),
        'post_status' => array( 'wc-completed' )
    ) );

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

    return $total;
}
Run Code Online (Sandbox Code Playgroud)

但是这个函数必须在 wp 完全加载时调用,所以如果你在你的 action 上使用这个函数woocommerce_payment_complete,它会起作用

希望能帮助到你