jagershark
jagershark

Reputation: 1241

Wordpress - Woocommerce - Retrieve orders for specific product

I am using the woocommerce wordpress plugin and I have retrieved a list of all orders using the WC_Order class. WC_Order documentation

This returns simple information about an order like ID, date and status but I need to know the product the customer bought.

So far my working code is:

$args = array(
    'post_type' => 'shop_order',
    'post_status' => 'publish',
    'meta_key' => '_customer_user',
    'posts_per_page' => '-1'
);

$my_query = new WP_Query($args);
$customer_orders = $my_query->posts;

$all_order_data = array();

foreach ($customer_orders as $customer_order) {
    $order = new WC_Order();
    $order->populate($customer_order);
    $orderdata = (array) $order;
    $all_order_data[] = $orderdata;
}

For easy viewing of the data I output it as json:

echo json_encode($all_order_data);

However, I need to be able to view what product's were purchased with each order. I cannot find a way to do this and I have not seen anything on the web about achieving this functionality. Likewise, if possible, retrieving orders that are attached to a product would be very important for me also.

Has anyone done this before? Or can anyone point me in the right direction?

Upvotes: 0

Views: 1154

Answers (2)

Brian Beinlich
Brian Beinlich

Reputation: 3

@helgatheviking was on the right track, but her sample code doesn't compile. All you need to do is replace

$orderdata = (array) $order;
$all_order_data[] = $orderdata;

with

$all_order_data[] = $order->get_items();

Hope this helps!

Upvotes: 0

helgatheviking
helgatheviking

Reputation: 26319

You can view the items in an order using the get_items() method on the order object. In my example, $all_order_data will be an array of all the items that have been purchased in the queried orders.

$customer_orders = new WP_Query($args);

$all_order_data = array();

while ($customer_orders->have_posts() ){
    $customer_orders->the_post();) {
    $order = new WC_Order();
    $all_order_data[] = $order->get_items();
}

wp_reset_postdata();

Upvotes: 0

Related Questions