Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Orders and Checkout

Orders and High-Performance Order Storage

Work with WooCommerce orders the safe way: HPOS tables, the compatibility declaration, wc_get_order, wc_get_orders, order meta and sync mode explained.

An order is the most valuable record in a store: it holds money, addresses, items and a history. For many years WooCommerce kept orders in the WordPress posts tables, as a post of type shop_order with dozens of rows of post meta. That worked for small shops, but it made big stores slow, because orders competed with blog posts and pages for the same tables and indexes. Today the default is High-Performance Order Storage (HPOS): dedicated tables built for orders.

For you as a plugin author the lesson is simple: never touch the storage directly. Go through the CRUD objects, exactly like for products in CRUD Classes and Data Stores, and your code works on both storage layouts. This lesson shows what HPOS looks like, how to declare compatibility, how to read, change and query orders, and how sync mode behaves. The real WooCommerce code is read-only; the runnable examples are stand-ins built on SQLite.

Posts storage versus HPOS

With HPOS enabled, the order data is spread over a few tables (the exact names carry your database prefix, such as wp_):

Table What it holds
wc_orders One row per order: ID, status, type, currency, totals, customer, dates, transaction ID.
wc_order_addresses The billing and shipping address of each order.
wc_order_operational_data Operational fields such as whether prices include tax, the created-via source and payment dates.
wc_orders_meta Custom meta, the replacement for wp_postmeta rows of orders.

Refunds are orders too (type shop_order_refund) and live in the same table. Order items and their meta (woocommerce_order_items, woocommerce_order_itemmeta) keep their own tables in both layouts.

flowchart LR
  P["Your plugin code"] --> C["WC_Order<br/>CRUD object"]
  C --> S["Order data store"]
  S -->|HPOS enabled| H["wc_orders and<br/>related tables"]
  S -->|posts storage| W["wp_posts and<br/>wp_postmeta"]

Your code talks to the CRUD object; the data store decides which tables are used.

The advantages are practical: order queries do not scan unrelated posts, the columns have proper types and indexes, and writing an order no longer locks the shared posts tables during busy sales.

Declare compatibility

HPOS is a store-wide switch, so WooCommerce asks every plugin whether it is safe. If your plugin does not answer, merchants see a warning and may be blocked from enabling HPOS. Declare it early, before WooCommerce initializes (the same hook you saw in Your First WooCommerce Extension):

PHP
<?php
use Automattic\WooCommerce\Utilities\FeaturesUtil;

add_action( 'before_woocommerce_init', function () {
    if ( class_exists( FeaturesUtil::class ) ) {
        FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
    }
} );

Only pass true after you have checked that the plugin follows the rules below. Declaring compatibility is a promise, not a formality.

Reading and changing orders

Use wc_get_order(). It takes an order ID (or an order object) and returns a WC_Order, a WC_Order_Refund, or false when nothing matches. Always check the result:

PHP
<?php
$order = wc_get_order( $order_id );

if ( ! $order instanceof WC_Order ) {
    return; // missing, or a refund
}

$total    = $order->get_total();           // string such as "59.90"
$status   = $order->get_status();          // "processing" (no wc- prefix)
$email    = $order->get_billing_email();
$customer = $order->get_customer_id();     // 0 for guests

foreach ( $order->get_items() as $item_id => $item ) {
    $name = $item->get_name();
    $qty  = $item->get_quantity();
}

Notice that get_status() returns processing, while the stored value is wc-processing. The prefix is an old convention from the posts days; the API hides it in most places. Use the API's form (without prefix) in your own code unless a function documents otherwise.

To change an order, use setters and then call save():

PHP
<?php
$order->set_billing_phone( '+49 30 1234567' );
$order->update_meta_data( '_acme_delivery_note', 'Leave at the door' );
$order->save();

update_meta_data() only marks the change; nothing is written until save(). That is the same change-tracking idea as for products, and it is what lets WooCommerce write only the columns that changed.

The one rule: never use post functions on orders

Under HPOS an order ID is not necessarily a post ID, and there is no wp_postmeta row to read. These all break or silently return nothing:

PHP
<?php
// Wrong: works only with posts storage.
$note = get_post_meta( $order_id, '_acme_delivery_note', true );
update_post_meta( $order_id, '_acme_delivery_note', 'x' );
$post = get_post( $order_id );
$query = new WP_Query( array( 'post_type' => 'shop_order' ) );

// Right: works with both.
$order = wc_get_order( $order_id );
$note  = $order->get_meta( '_acme_delivery_note' );
$order->update_meta_data( '_acme_delivery_note', 'x' );
$order->save();

Also avoid raw SQL against wp_posts or wp_postmeta for orders. If you must check which storage is active, use the helper in Automattic\WooCommerce\Utilities\OrderUtil, such as OrderUtil::custom_orders_table_usage_is_enabled(), and prefer branching as little as possible.

The class that implements HPOS storage is Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore. The word "Internal" in the namespace tells you not to depend on it. Extend behavior through CRUD methods and hooks, not through that class.

Querying with wc_get_orders

wc_get_orders() is the supported replacement for get_posts() and WP_Query on orders. It takes an array of arguments:

PHP
<?php
$orders = wc_get_orders( array(
    'status'       => array( 'processing', 'on-hold' ),
    'customer_id'  => 42,
    'date_created' => '>=' . strtotime( '-30 days' ),
    'orderby'      => 'date',
    'order'        => 'DESC',
    'limit'        => 20,
) );

// Only IDs, cheaper when you do not need objects:
$ids = wc_get_orders( array( 'status' => 'completed', 'limit' => -1, 'return' => 'ids' ) );

// With pagination information:
$result = wc_get_orders( array( 'limit' => 20, 'paginate' => true, 'paged' => 2 ) );
// $result->orders, $result->total, $result->max_num_pages

Be careful with 'limit' => -1 on a large shop: it loads everything. For exports and reports, page through the results or use a background job (Background Processing With Action Scheduler). Searching custom meta works through meta_query-style arguments, but a meta lookup on a large table is slow unless it is indexed; if you need to find orders by your own value often, consider storing it in your own indexed table.

Migration and sync mode

When a merchant switches to HPOS, existing orders have to be copied into the new tables. WooCommerce offers a compatibility mode (also called sync mode): every write goes to both layouts, so plugins that still read the old tables see current data. The merchant can later turn sync off to get the full speed benefit.

This explains a common bug report: a plugin that reads wp_postmeta directly seems fine while sync is on and breaks the day sync is switched off. The moral is the same as before: use the CRUD API, and you will not notice which mode is active.

New stores start with HPOS as the default, and WooCommerce keeps its posts-based storage for older installs. Plan for both.

A runnable order repository

This stand-in is not WooCommerce. It shows the ideas of this lesson with SQLite: separate tables for orders and meta, a status stored with a prefix but exposed without it, change tracking (only changed columns are written), and a wc_get_orders()-style query with filters, limit and an ID-only mode.

PHP An order repository with change tracking and queries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

What is real and what is not: the table split, the wc- prefix hidden by the getter, the "write only what changed" idea and the wc_get_orders() arguments follow WooCommerce. The SQL, the class names and the tiny feature set are the stand-in.

What sync mode protects you from

The next demo models two storages and a plugin that reads the old one directly. With sync on, both stores receive every write and the "wrong" plugin appears to work. Turn sync off and it reads stale data. The CRUD route reads from the authoritative store and is always right.

PHP Why direct reads break when sync is switched off

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call reads a custom value stored on an order in a way that works with HPOS and with posts storage?

    The CRUD object knows which data store is active. The post functions and raw SQL on wp_postmeta only work with posts storage, and break when HPOS is authoritative.
  2. 2. What should you do so that WooCommerce does not warn merchants about your plugin when they enable HPOS?

    FeaturesUtil::declare_compatibility() on before_woocommerce_init is the supported declaration. It is a promise, so declare it only after checking the plugin follows the CRUD rules.
  3. 3. What does wc_get_order() return when the ID does not exist?

    It returns false (or a WC_Order_Refund for refund IDs). Check with instanceof WC_Order before using the result.
  4. 4. A plugin reads order meta directly from wp_postmeta and seems fine on the developer's site. Why might it fail at a customer's site?

    Sync mode writes to both layouts and hides the problem. Once sync is off, only the HPOS tables receive writes, and the old reads return stale or empty data.

Summary

  • HPOS stores orders in dedicated tables (wc_orders, addresses, operational data, wc_orders_meta) instead of posts and post meta.
  • Declare compatibility with FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true ) on before_woocommerce_init, but only when it is true.
  • Read with wc_get_order() (check for false), change with setters and update_meta_data(), and persist with save().
  • Never use get_post_meta, get_post, WP_Query or raw SQL on wp_posts for orders; use wc_get_orders() for queries and page through large results.
  • Sync mode keeps both layouts current for a while, which hides bugs in direct-storage code.
  • The runnable repositories are stand-ins that demonstrate the ideas, not WooCommerce itself.

Next: Order Statuses and the Order Lifecycle