Querying WooCommerce orders

daniel bradley 702681 unsplash

I recently discovered WC_Order_Query, which is essentially WooCommerce’s version of WP_Query but specifically for orders.

Here’s an example of how to query completed orders by date:

$args = array(
'limit' => 9999,
'return' => 'ids',
'date_completed' => '2018-10-01...2018-10-10',
'status' => 'completed'
$query = new WC_Order_Query( $args );
$orders = $query->get_orders();
foreach( $orders as $order_id ) {
// ...

It follows a similar structure to WP_Query. Note that I’ve just requested the IDs, in order to make the query a lot lighter, and the very neat and easy way to query between dates. There is a fuller list of parameters on the WooCommerce Github wiki page.

Get customer details from a WooCommerce order

Once you’ve got your order, you probably want to extract some data. Using the order number, create an $order object, then use get_user_id to obtain the customer’s user ID:

$order = wc_get_order( $order_id );
$customer_id = $order->get_user_id();

Get billing details from WooCommerce order

If you want to grab useful information like the customer’s email, phone number, name, address, etc, you can do it just using the $order object:

$order = wc_get_order( $order_id );
echo $order->get_billing_email();
echo $order->get_billing_first_name();
echo $order->get_billing_last_name();
echo $order->get_billing_address_1();
echo $order->get_billing_address_2();
echo $order->get_billing_postcode();
echo $order->get_billing_state();
echo $order->get_billing_country();
echo $order->get_billing_phone();

As you can see, WooCommerce has a load of simple methods to return useful customer information.


Leave a Reply

Your email address will not be published. All fields are required.