1

Wordpress Version 5.3.2 Woocommerce Version 3.8.1

To acheive Show user his purchased orders along with order_items (products in the order)

What I have tried

Saw How to get WooCommerce order details , Get some order and order items data in Woocommerce emails ,https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query

Still couldn't solve my issue.

Error I am facing

Fatal error: Uncaught Error: Call to a member function get_id() on array

Code

//got the user
$user = wp_get_current_user();
//In my case $user->ID returns 1

$args = array(
    'customer_id' => $user->ID,
    'status' => 'confirmed',
);
//Since i only want the confirmed orders
$order= wc_get_orders( $args );
$order_id  = $order->get_id();
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175

2 Answers2

1

I was struggling a bit more after the accepted solution. Initially i was getting a complete array of orders, After iterating through that array i found what i was looking for.

    $user = wp_get_current_user();
    $args = array(
    //'customer_id' => $user->ID
    'customer_id' => 6
);
    $orders = wc_get_orders($args);
    foreach($orders as $order){
        $order_id  = $order->get_id();        
        echo $order_id . "<br/>";
    }

This foreach allowed accessing the order_id i required.

0

As you can see from the docs, wc_get_orders returns an array or stdClass. The error message tells you that you cannot call get_id of an array, so you have an array. Because the customer you are searching with has multiple confirmed orders. Solution:

//...
$orders = wc_get_orders( $args );
if (!is_array($orders)) $orders = [$orders];
//...
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175