Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 ยท Products and the CRUD Layer

CRUD Classes and Data Stores

Learn how WC_Data, getters and setters, change tracking and data stores work in WooCommerce, and why you should never write product or order meta directly.

Older WooCommerce code read prices with get_post_meta( $id, '_price', true ) and wrote them with update_post_meta(). That worked while products were always posts, but it hard-wires your plugin to one storage layout. Modern WooCommerce puts a layer in between: CRUD classes that represent a thing (a product, an order, a coupon, a customer) and data stores that know where and how it is saved.

This lesson explains that layer, because every later lesson in this chapter builds on it. You will see how an object tracks changes, what save() really does, why direct meta access is a trap, and how a data store can be replaced. The platform code is shown read-only (it cannot run on this site); two runnable stand-ins reproduce the ideas in plain PHP and SQLite. If you need the big picture first, read How WooCommerce Is Built.

Objects, not rows

CRUD stands for create, read, update, delete. In WooCommerce the base class is WC_Data. Products (WC_Product), orders (WC_Order), coupons (WC_Coupon) and customers (WC_Customer) all extend it, directly or indirectly. A WC_Data object holds three things:

  • an ID (zero for a new, unsaved object),
  • a data array with the current known values (name, price, SKU and so on),
  • a changes array with values you have set but not yet saved.

The object does not talk to the database itself. It owns a data store, a separate class with create, read, update and delete methods. The object calls the store, and the store runs the queries.

flowchart LR
    A["Your plugin code"] --> B["WC_Product<br/>(getters, setters, changes)"]
    B -->|"save()"| C["WC_Product_Data_Store_CPT"]
    C --> D[("posts, postmeta,<br/>lookup tables")]
    B -.->|"swapped store"| E["Custom data store"]
    E -.-> F[("Another table or service")]

The object stays the same; only the data store decides where the data lives.

Getters, setters and contexts

You never assign properties. You call setters and getters, which every CRUD class provides:

PHP
$product = wc_get_product( 123 );

$product->set_name( 'Trail Backpack' );
$product->set_regular_price( '89.00' );
$product->set_sku( 'BP-TRAIL-01' );

$product->save();

Setters do not write to the database. They record the change inside the object. Only save() persists them. That gives you atomic-looking updates: set ten properties, save once.

Getters accept a context argument. The default is 'view', which runs the value through filters so extensions can adjust what shoppers see (the filter names look like woocommerce_product_get_name). The context 'edit' skips those filters and returns the raw stored value, which is what admin screens and your own save logic usually want:

PHP
$display_name = $product->get_name();         // 'view': filtered
$raw_name     = $product->get_name( 'edit' ); // 'edit': raw

When you read a value only to modify and save it, use the 'edit' context. Reading the filtered 'view' value and saving it back can write a discounted or translated value into the database permanently.

Change tracking

When an object is read from storage, it is marked as "read". From then on, setters write into the changes array and only when the new value differs from the stored one. A save() with no changes does nothing expensive, and an update touches only the fields that changed.

This is the first stand-in. It reproduces the mechanism with a tiny entity base class, so you can watch values move from "changed" to "stored".

PHP A change-tracking entity (stand-in for WC_Data)

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.

In the real classes, the 'view' filter hooks make this pattern powerful: pricing and display plugins hook the getters without ever touching storage. It is also why the 'edit' context matters.

What save() does

Calling $product->save() roughly follows these steps:

  1. Fire a "before save" action (for products, woocommerce_before_product_object_save).
  2. If the ID is zero, call the data store's create(). Otherwise call update().
  3. The store writes only what changed, then the object applies its changes and clears the changes array.
  4. Save any changed custom meta data (see below).
  5. Fire an "after save" action (woocommerce_after_product_object_save).

Because those hooks fire for every save from anywhere (admin screen, REST API, importer, your own code), they are the best place to react to a product being stored. Hooking save_post instead misses saves from stores that do not use posts. Delete follows the same idea: $product->delete() moves the object to the trash, and $product->delete( true ) removes it permanently.

Custom meta through the object

Extensions often attach their own data to products or orders. Use the object's meta methods rather than WordPress's meta functions:

PHP
$product = wc_get_product( $product_id );

$product->update_meta_data( '_acme_gift_wrap', 'yes' );
$product->save(); // saves changed props and changed meta

$wrap = $product->get_meta( '_acme_gift_wrap', true );

update_meta_data() only stages the change inside the object; save() (or save_meta_data()) writes it. Meta is loaded together with the object, so reading ten keys does not run ten queries.

Why not touch post meta directly?

Calling update_post_meta( $order_id, ... ) assumes data lives in the posts tables. That assumption is already false for orders on stores that use High-Performance Order Storage (covered in Orders and High-Performance Order Storage): the order is in dedicated tables, and your write lands in a place WooCommerce never reads. Even for products, direct writes skip:

  • the "before/after save" hooks, so caches and lookup tables go stale,
  • validation done in setters (for example price formatting),
  • the object cache the CRUD layer keeps in sync.

The rule is simple: read and write through the CRUD object. Use raw SQL or post meta only for your own custom tables, where you own the schema (see WPDB and Custom Tables).

Data stores and swapping

Each object type asks WC_Data_Store::load( 'product' ) for its store. WooCommerce keeps a map from type name to store class, and a filter lets an extension replace an entry:

PHP
add_filter( 'woocommerce_data_stores', function ( array $stores ): array {
    $stores['product'] = 'Acme_Product_Data_Store';
    return $stores;
} );

A replacement should usually extend the default store and override only what differs, because the default one also maintains lookup tables, stock status and transients. Replacing a store wholesale is an advanced move: do it only when the data truly lives elsewhere, and test every code path (admin, REST, import, cart).

The second stand-in shows the pattern with SQLite: one entity class, two interchangeable stores, and a log that proves an update writes only the changed column.

PHP Swapping data stores (SQLite stand-in)

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 here: the object-plus-store split, change tracking and the "write only what changed" behaviour. What is the stand-in: the classes themselves, which are far smaller than WC_Data and WC_Data_Store, and the SQLite tables, which are not WooCommerce's schema.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does calling $product->set_name( 'New' ) do?

    Setters only stage changes in the object. save() asks the data store to persist them.
  2. 2. When should you use the 'edit' context of a getter?

    The 'edit' context returns the raw stored value without view filters, so you do not accidentally save a filtered or discounted value.
  3. 3. Why is update_post_meta() on an order a bad idea in a modern store?

    With High-Performance Order Storage orders are not posts. The CRUD object hides that difference; raw post meta does not.
  4. 4. How should a plugin react to every product save, whatever its source?

    The object-level save hooks fire for admin, REST, imports and code. save_post only covers post-based storage.

Summary

  • CRUD classes (WC_Product, WC_Order, ...) represent things; data stores decide where they are stored.
  • Setters stage changes, save() persists only what changed and fires before/after hooks.
  • Use the 'edit' context when reading a value you intend to save back.
  • Store extra data with update_meta_data() and get_meta() on the object, not with post meta functions.
  • Swapping a data store is possible through woocommerce_data_stores, but extend the default store unless the data truly lives elsewhere.

Next: Working With Products in Code