How to Get Order Details by Order ID

Wondering how to get the WooCommerce full order details by Order ID? Don't worry in this tutorial I have written one function that will help to get the details in a fraction of a second.

Every eCommerce business owner knows that managing orders efficiently is the key to customer satisfaction. But what happens when you need to access specific details of a particular order quickly? That's where retrieving WooCommerce order details by Order ID comes to the rescue. This vital function enables you to streamline your operations, address customer inquiries, and even enhance your business analytics. In this tutorial, we'll explore the significance of this function and guide you through its implementation, ensuring you have the tools to excel in managing your WooCommerce store.

WooCommerce 3.x or above

<?php

if (!function_exists('getOrderDetailById')) {

    //to get full order details
    function getOrderDetailById($id, $fields = null, $filter = array()) {

        if (is_wp_error($id))
            return false;

        // Get the decimal precession
        $dp = (isset($filter['dp'])) ? intval($filter['dp']) : 2;
        $order = wc_get_order($id); //getting order Object

        if ($order === false)
            return false;

        $order_data = array(
            'id' => $order->get_id(),
            'order_number' => $order->get_order_number(),
            'created_at' => $order->get_date_created()->date('Y-m-d H:i:s'),
            'updated_at' => $order->get_date_modified()->date('Y-m-d H:i:s'),
            'completed_at' => !empty($order->get_date_completed()) ? $order->get_date_completed()->date('Y-m-d H:i:s') : ",
            'status' => $order->get_status(),
            'currency' => $order->get_currency(),
            'total' => wc_format_decimal($order->get_total(), $dp),
            'subtotal' => wc_format_decimal($order->get_subtotal(), $dp),
            'total_line_items_quantity' => $order->get_item_count(),
            'total_tax' => wc_format_decimal($order->get_total_tax(), $dp),
            'total_shipping' => wc_format_decimal($order->get_total_shipping(), $dp),
            'cart_tax' => wc_format_decimal($order->get_cart_tax(), $dp),
            'shipping_tax' => wc_format_decimal($order->get_shipping_tax(), $dp),
            'total_discount' => wc_format_decimal($order->get_total_discount(), $dp),
            'shipping_methods' => $order->get_shipping_method(),
            'order_key' => $order->get_order_key(),
            'payment_details' => array(
                'method_id' => $order->get_payment_method(),
                'method_title' => $order->get_payment_method_title(),
                'paid_at' => !empty($order->get_date_paid()) ? $order->get_date_paid()->date('Y-m-d H:i:s') : ",
            ),
            'billing_address' => array(
                'first_name' => $order->get_billing_first_name(),
                'last_name' => $order->get_billing_last_name(),
                'company' => $order->get_billing_company(),
                'address_1' => $order->get_billing_address_1(),
                'address_2' => $order->get_billing_address_2(),
                'city' => $order->get_billing_city(),
                'state' => $order->get_billing_state(),
                'formated_state' => WC()->countries->states[$order->get_billing_country()][$order->get_billing_state()], //human readable formated state name
                'postcode' => $order->get_billing_postcode(),
                'country' => $order->get_billing_country(),
                'formated_country' => WC()->countries->countries[$order->get_billing_country()], //human readable formated country name
                'email' => $order->get_billing_email(),
                'phone' => $order->get_billing_phone()
            ),
            'shipping_address' => array(
                'first_name' => $order->get_shipping_first_name(),
                'last_name' => $order->get_shipping_last_name(),
                'company' => $order->get_shipping_company(),
                'address_1' => $order->get_shipping_address_1(),
                'address_2' => $order->get_shipping_address_2(),
                'city' => $order->get_shipping_city(),
                'state' => $order->get_shipping_state(),
                'formated_state' => WC()->countries->states[$order->get_shipping_country()][$order->get_shipping_state()], //human readable formated state name
                'postcode' => $order->get_shipping_postcode(),
                'country' => $order->get_shipping_country(),
                'formated_country' => WC()->countries->countries[$order->get_shipping_country()] //human readable formated country name
            ),
            'note' => $order->get_customer_note(),
            'customer_ip' => $order->get_customer_ip_address(),
            'customer_user_agent' => $order->get_customer_user_agent(),
            'customer_id' => $order->get_user_id(),
            'view_order_url' => $order->get_view_order_url(),
            'line_items' => array(),
            'shipping_lines' => array(),
            'tax_lines' => array(),
            'fee_lines' => array(),
            'coupon_lines' => array(),
        );

        //getting all line items
        foreach ($order->get_items() as $item_id => $item) {

            $product = $item->get_product();

            $product_id = null;
            $product_sku = null;
            // Check if the product exists.
            if (is_object($product)) {
                $product_id = $product->get_id();
                $product_sku = $product->get_sku();
            }

            $order_data['line_items'][] = array(
                'id' => $item_id,
                'subtotal' => wc_format_decimal($order->get_line_subtotal($item, false, false), $dp),
                'subtotal_tax' => wc_format_decimal($item['line_subtotal_tax'], $dp),
                'total' => wc_format_decimal($order->get_line_total($item, false, false), $dp),
                'total_tax' => wc_format_decimal($item['line_tax'], $dp),
                'price' => wc_format_decimal($order->get_item_total($item, false, false), $dp),
                'quantity' => wc_stock_amount($item['qty']),
                'tax_class' => (!empty($item['tax_class']) ) ? $item['tax_class'] : null,
                'name' => $item['name'],
                'product_id' => (!empty($item->get_variation_id()) && ('product_variation' === $product->post_type )) ? $product->get_parent_id() : $product_id,
                'variation_id' => (!empty($item->get_variation_id()) && ('product_variation' === $product->post_type )) ? $product_id : 0,
                'product_url' => get_permalink($product_id),
                'product_thumbnail_url' => wp_get_attachment_image_src(get_post_thumbnail_id($product_id), 'thumbnail', TRUE)[0],
                'sku' => $product_sku,
                'meta' => wc_display_item_meta($item, ['echo' => false])
            );
        }

        //getting shipping
        foreach ($order->get_shipping_methods() as $shipping_item_id => $shipping_item) {
            $order_data['shipping_lines'][] = array(
                'id' => $shipping_item_id,
                'method_id' => $shipping_item['method_id'],
                'method_title' => $shipping_item['name'],
                'total' => wc_format_decimal($shipping_item['cost'], $dp),
            );
        }

        //getting taxes
        foreach ($order->get_tax_totals() as $tax_code => $tax) {
            $order_data['tax_lines'][] = array(
                'id' => $tax->id,
                'rate_id' => $tax->rate_id,
                'code' => $tax_code,
                'title' => $tax->label,
                'total' => wc_format_decimal($tax->amount, $dp),
                'compound' => (bool) $tax->is_compound,
            );
        }

        //getting fees
        foreach ($order->get_fees() as $fee_item_id => $fee_item) {
            $order_data['fee_lines'][] = array(
                'id' => $fee_item_id,
                'title' => $fee_item['name'],
                'tax_class' => (!empty($fee_item['tax_class']) ) ? $fee_item['tax_class'] : null,
                'total' => wc_format_decimal($order->get_line_total($fee_item), $dp),
                'total_tax' => wc_format_decimal($order->get_line_tax($fee_item), $dp),
            );
        }

        //getting coupons
        foreach ($order->get_items('coupon') as $coupon_item_id => $coupon_item) {

            $order_data['coupon_lines'][] = array(
                'id' => $coupon_item_id,
                'code' => $coupon_item['name'],
                'amount' => wc_format_decimal($coupon_item['discount_amount'], $dp),
            );
        }

        return array('order' => apply_filters('woocommerce_api_order_response', $order_data, $order, $fields));
    }

}

WooCommerce 2.6.x or below

<?php

if (!function_exists('getOrderDetailById')) {

function getOrderDetailById($id, $fields = null, $filter = array()) {

if (is_wp_error($id))
return $id;

// Get the decimal precession
$dp = isset($filter['dp']) ? intval($filter['dp']) : 2;
$order = wc_get_order($id);
$order_post = get_post($id);

$order_data = array(
'id' => $order->id,
'order_number' => $order->get_order_number(),
'created_at' => $order_post->post_date,
'updated_at' => $order_post->post_modified,
'completed_at' => !empty($order->completed_date) ? $order->completed_date : ",
'status' => $order->get_status(),
'currency' => $order->get_order_currency(),
'total' => wc_format_decimal($order->get_total(), $dp),
'subtotal' => wc_format_decimal($order->get_subtotal(), $dp),
'total_line_items_quantity' => $order->get_item_count(),
'total_tax' => wc_format_decimal($order->get_total_tax(), $dp),
'total_shipping' => wc_format_decimal($order->get_total_shipping(), $dp),
'cart_tax' => wc_format_decimal($order->get_cart_tax(), $dp),
'shipping_tax' => wc_format_decimal($order->get_shipping_tax(), $dp),
'total_discount' => wc_format_decimal($order->get_total_discount(), $dp),
'shipping_methods' => $order->get_shipping_method(),
'order_key' => $order->order_key,
'payment_details' => array(
'method_id' => $order->payment_method,
'method_title' => $order->payment_method_title,
'paid_at' => !empty($order->paid_date) ? $order->paid_date : ",
),
'billing_address' => array(
'first_name' => $order->billing_first_name,
'last_name' => $order->billing_last_name,
'company' => $order->billing_company,
'address_1' => $order->billing_address_1,
'address_2' => $order->billing_address_2,
'city' => $order->billing_city,
'state' => $order->billing_state,
'formated_state' => WC()->countries->states[$order->billing_country][$order->billing_state], //human readable formated state name
'postcode' => $order->billing_postcode,
'country' => $order->billing_country,
'formated_country' => WC()->countries->countries[$order->billing_country], //human readable formated country name
'email' => $order->billing_email,
'phone' => $order->billing_phone,
),
'shipping_address' => array(
'first_name' => $order->shipping_first_name,
'last_name' => $order->shipping_last_name,
'company' => $order->shipping_company,
'address_1' => $order->shipping_address_1,
'address_2' => $order->shipping_address_2,
'city' => $order->shipping_city,
'state' => $order->shipping_state,
'formated_state' => WC()->countries->states[$order->shipping_country][$order->shipping_state], //human readable formated state name
'postcode' => $order->shipping_postcode,
'country' => $order->shipping_country,
'formated_country' => WC()->countries->countries[$order->shipping_country] //human readable formated country name
),
'note' => $order->customer_note,
'customer_ip' => $order->customer_ip_address,
'customer_user_agent' => $order->customer_user_agent,
'customer_id' => $order->get_user_id(),
'view_order_url' => $order->get_view_order_url(),
'line_items' => array(),
'shipping_lines' => array(),
'tax_lines' => array(),
'fee_lines' => array(),
'coupon_lines' => array(),
);

//getting all line items
foreach ($order->get_items() as $item_id => $item) {

$product = $order->get_product_from_item($item);
$product_id = null;
$product_sku = null;

// Check if the product exists.
if (is_object($product)) {
$product_id = !empty($product->variation_id) ? $product->variation_id : $product->id;
$product_sku = $product->get_sku();
}

$meta = new WC_Order_Item_Meta($item, $product);

$item_meta = array();

$hideprefix = ( isset($filter['all_item_meta']) && $filter['all_item_meta'] === 'true' ) ? null : '_';

foreach ($meta->get_formatted($hideprefix) as $meta_key => $formatted_meta) {
$item_meta[] = array(
'key' => $formatted_meta['key'],
'label' => $formatted_meta['label'],
'value' => $formatted_meta['value'],
);
}

$order_data['line_items'][] = array(
'id' => $item_id,
'subtotal' => wc_format_decimal($order->get_line_subtotal($item, false, false), $dp),
'subtotal_tax' => wc_format_decimal($item['line_subtotal_tax'], $dp),
'total' => wc_format_decimal($order->get_line_total($item, false, false), $dp),
'total_tax' => wc_format_decimal($item['line_tax'], $dp),
'price' => wc_format_decimal($order->get_item_total($item, false, false), $dp),
'quantity' => wc_stock_amount($item['qty']),
'tax_class' => (!empty($item['tax_class']) ) ? $item['tax_class'] : null,
'name' => $item['name'],
'product_id' => !empty($product->variation_id) ? $product->parent_id : $product_id,
'variation_id' => !empty($product->variation_id) ? $product_id : 0,
'sku' => $product_sku,
'product_url' => get_permalink($product_id),
'product_thumbnail_url' => wp_get_attachment_image_src(get_post_thumbnail_id($product_id), 'thumbnail', TRUE)[0],
'meta' => $item_meta,
);
}

//getting shipping
foreach ($order->get_shipping_methods() as $shipping_item_id => $shipping_item) {

$order_data['shipping_lines'][] = array(
'id' => $shipping_item_id,
'method_id' => $shipping_item['method_id'],
'method_title' => $shipping_item['name'],
'total' => wc_format_decimal($shipping_item['cost'], $dp),
);
}

//getting taxes
foreach ($order->get_tax_totals() as $tax_code => $tax) {
$order_data['tax_lines'][] = array(
'id' => $tax->id,
'rate_id' => $tax->rate_id,
'code' => $tax_code,
'title' => $tax->label,
'total' => wc_format_decimal($tax->amount, $dp),
'compound' => (bool) $tax->is_compound,
);
}

//getting fees
foreach ($order->get_fees() as $fee_item_id => $fee_item) {
$order_data['fee_lines'][] = array(
'id' => $fee_item_id,
'title' => $fee_item['name'],
'tax_class' => (!empty($fee_item['tax_class']) ) ? $fee_item['tax_class'] : null,
'total' => wc_format_decimal($order->get_line_total($fee_item), $dp),
'total_tax' => wc_format_decimal($order->get_line_tax($fee_item), $dp),
);
}

//getting coupons
foreach ($order->get_items('coupon') as $coupon_item_id => $coupon_item) {
$order_data['coupon_lines'][] = array(
'id' => $coupon_item_id,
'code' => $coupon_item['name'],
'amount' => wc_format_decimal($coupon_item['discount_amount'], $dp),
);
}

return array('order' => apply_filters('woocommerce_api_order_response', $order_data, $order, $fields));
}

}


Step-by-Step Explanation

  1. Function Existence Check: The code checks if the getOrderDetailById the function already exists, ensuring it's defined only once.
  2. Function Definition: getOrderDetailById is defined with three parameters:
    • $id: The Order ID you want to retrieve details for.
    • $fields: An optional parameter to specify which fields to retrieve (not used in this code).
    • $filter: An optional parameter for additional filtering options (not used in this code).
  3. Check for Error: The code verifies if the provided Order ID is a WordPress error object. If it is, the function returns false to indicate an error.
  4. Get Decimal Precision: The code calculates the decimal precision used for formatting monetary values. If the $filter array contains a 'dp' key, it converts it to an integer; otherwise, the precision is set to 2.
  5. Retrieve Order Object: Using the wc_get_order function from WooCommerce, the code retrieves the Order Object for the given Order ID.
  6. Check for Order Existence: Verification is essential to confirm that the order object was successfully retrieved. If not, the function returns false.
  7. Order Data Extraction: The code extracts various order-related information, including order number, dates, status, currency, and more.
  8. Payment Details: Payment details, such as the payment method, title, and paid date, are extracted.
  9. Billing and Shipping Addresses: Billing and shipping address information is collected, including names, addresses, states, and more.
  10. Line Items: Details about each line item in the order are collected, encompassing subtotals, totals, prices, quantities, and more.
  11. Shipping Methods: Shipping methods used for the order are collected, including their IDs, titles, and costs.
  12. Taxes: Information regarding taxes applied to the order is extracted, including tax code, title, total, and whether it's a compound tax.
  13. Fees: Any fees associated with the order are collected, including the fee's title, tax class, total, and total tax.
  14. Coupons: Information about any coupons applied to the order is extracted, including coupon codes and amounts.
  15. Filtering and Returning Data: The collected order data is structured into an array, and some filtering is applied using the apply_filters function. Finally, the function returns this order data.

Okay now, how do I use it?

First, add getOrderDetailById() to your active theme functions.php or to any active plugin PHP file.
Then call getOrderDetailById() from anywhere in your app bypassing the Order ID like below.

<?php

$order_detail = getOrderDetailById(101); //to get the detail of order ID #101
print_r($order_detail);

Using WooCommerce Shipment Tracking and want to add that as well?

WooCommerce Shipment Tracking is an awesome paid plugin that you must have! If you want to add this in your custom order detail function then just add the below code in the above mentions.

For Shipment Tracking 1.4.0 or above

<?php

$order_id = method_exists($order, 'get_id') ? $order->get_id() : $order->id;

//getting shipping details
$objWC_Shipment = WC_Shipment_Tracking_Actions::get_instance();
$shipping_details = $objWC_Shipment->get_tracking_items($order_id);
if (!empty($shipping_details)) {
foreach ($shipping_details as $shipping_detail) {
$order_data['shipping_details'][] = array(
'tracking_provider' => $shipping_detail['tracking_provider'],
'tracking_number' => $shipping_detail['tracking_number'],
'date_shipped' => $shipping_detail['date_shipped']
);
}
}

For Shipment Tracking 1.3.6 or below

<?php

$order_id = method_exists($order, 'get_id') ? $order->get_id() : $order->id;

//getting shipping details
$tracking_number = get_post_meta($order_id, '_tracking_number', TRUE);
if (isset($tracking_number) && !empty($tracking_number)) {
$order_data['shipping_details'] = array(
'tracking_provider' => get_post_meta($order_id, '_tracking_provider', TRUE),
'tracking_number' => $tracking_number,
'date_shipped' => get_post_meta($order_id, '_date_shipped', TRUE)
);
}

Congratulations! You've now acquired a valuable tool in your WooCommerce arsenal – that allows you to easily retrieve a detailed list of order information. This tutorial has provided valuable insights into how you can efficiently access everything from order numbers to billing information. But, our journey doesn't end here. We're here to help you explore even more secrets of the WooCommerce platform. If you found this tutorial helpful, we encourage you to continue with the next chapter of our WooCommerce DB series - "Unlocking Order Data Mysteries: Part 2 of the WooCommerce DB Series". This next part will provide you with advanced insights and techniques to enhance your WooCommerce experience.

We value your feedback and would be delighted to answer any questions you may have. If you found this tutorial helpful, please consider sharing it with others who may benefit from it. If you have any queries, require further clarification or would like to express your appreciation, please leave a comment below. Your input motivates us to provide excellent, informative content. Thank you for being part of our WooCommerce community!

Raunak Gupta

Raunak Gupta

I'm Raunak Gupta, a seasoned software developer with over 9 years of experience in a wide range of programming languages, frameworks, and tools. I started my journey as a WordPress & CakePHP developer in 2014, diving deep into the world of OOPs, Request handling, and SEO. Along the way, I crafted numerous dazzling WooCommerce stores, tamed payment gateways, optimized for full filament functionality, and achieved ultra-low latency for lightning-fast load times. My expertise extends to BI tools, website builders, DevOps, and team leadership. I like to help upcoming developers, so I share my experience through this blog and by assisting fellow developers on Stack Overflow, where I've earned a stellar reputation with over 10k+ points of recognition.

Articles: 29

12 Comments

  1. $order = wc_get_order(20);

    while using above code,i m getting error as

    Fatal error: Call to a member function get_id() on boolean in.

    Please let me know, where i did mistake.

    Thanks in advance.

  2. Hi, I’m getting this:

    Warning: Missing argument 4 for WC_PB_REST_API::legacy_order_response() in (…)/wp-content/plugins/woocommerce-product-bundles/includes/class-wc-pb-rest-api.php on line 1074

  3. Hello! I’m at work browsing your blog from my new apple iphone!

    Just wanted to say I love reading your blog and look forward to all
    your posts! Carry on the superb work!

  4. This is what I was lookin’ for, eh? Thank ya kindly. And I’m also a follower of ya in SO, ya know. Can ya also write an article on woocommerce order schema, eh?

Leave a Reply

Your email address will not be published. Required fields are marked *