Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 68 ยท Performance, Tools and Scaling

WooCommerce Basics

Learn how WooCommerce stores products and orders, how HPOS changes order storage, how cart and checkout flow, and how to extend a shop safely with hooks.

WooCommerce is a plugin that turns WordPress into an online shop. It is not a separate system: it builds on everything you have already learned. Products are a custom post type, product categories are a custom taxonomy, settings live in options, and almost every behavior can be changed with actions and filters. If you understand those pieces, WooCommerce stops feeling like magic.

This lesson gives you the map: how products and orders are stored, how the cart and checkout flow works, which functions and classes you call from code, which hooks you will meet first, and how to customize a shop without breaking it on the next update. Money handling is where small mistakes become expensive, so you will also build a runnable totals calculator.

WooCommerce needs WordPress, MySQL or MariaDB and a web server, so none of it can run on this site. All real WooCommerce code below is read-only. The runnable examples are plain-PHP stand-ins that copy the ideas (integer money, a cart, an order lifecycle with hooks). They are not WooCommerce code, and real WooCommerce has many more rules than shown here.

What WooCommerce adds to WordPress

When you activate WooCommerce it registers several things in the places you already know:

  • A post type named product, plus taxonomies product_cat (categories), product_tag (tags) and others for attributes.
  • Pages for the shop, cart, checkout and "My account", created on first setup.
  • Tables of its own for orders (more on that in a moment), sessions, tax rates, shipping zones and a few more.
  • A large set of template files, hooks and a REST API under /wp-json/wc/v3/.

Everything else, such as payment gateways, shipping methods and fancy product types, is added by extensions that use the same hooks you can use.

Products

A product is a post of type product, with its price, SKU, stock and other facts stored as post meta (for example _price and _regular_price). You almost never read those meta keys directly. Instead you ask for a product object:

PHP
<?php
$product = wc_get_product( 123 );

if ( ! $product ) {
    return; // Not found, or not a product.
}

echo $product->get_name();
echo $product->get_sku();
echo $product->get_price();          // Current price as a string, e.g. "19.99".
echo $product->get_regular_price();
echo $product->is_in_stock() ? 'In stock' : 'Out of stock';
echo wc_price( $product->get_price() ); // Formatted with the shop's currency symbol.

wc_get_product() returns an object of a class that depends on the product type: WC_Product_Simple, WC_Product_Variable (with variations such as size and color), WC_Product_Grouped and WC_Product_External. All share the WC_Product base class, so the getters above work for every type. Changing a product follows the same pattern as every WooCommerce data object: set, then save.

PHP
<?php
$product = wc_get_product( 123 );
$product->set_regular_price( '24.00' );
$product->set_stock_quantity( 10 );
$product->save();

Using getters and setters rather than raw meta keeps your code working when WooCommerce changes how data is stored internally. That is exactly what happened with orders.

Orders and HPOS

When a customer checks out, WooCommerce creates an order. For many years orders were stored as posts of type shop_order, with every address line and total sitting in wp_postmeta. On a busy shop that makes the posts and meta tables huge and slow (see the database schema for why the meta table is expensive).

High-Performance Order Storage (HPOS) moves orders into dedicated tables such as wc_orders, wc_orders_meta, wc_order_addresses and wc_order_operational_data. They have proper columns for totals, status and customer, so queries are faster and the posts table stays clean. HPOS is the default for new stores on recent WooCommerce versions, and older stores can migrate to it.

The practical rule for plugin authors: never read or write order data with get_post_meta() or WP_Query. Use the order object and the order functions, which work with either storage:

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

if ( ! $order ) {
    return;
}

echo $order->get_id();
echo $order->get_status();           // "processing", without a "wc-" prefix.
echo $order->get_total();
echo $order->get_billing_email();
echo $order->get_meta( '_gift_note' ); // Your own data on the order.

foreach ( $order->get_items() as $item ) {
    echo $item->get_name() . ' x ' . $item->get_quantity();
}

$order->update_meta_data( '_gift_note', 'Happy birthday' );
$order->add_order_note( 'Gift note added by Acme plugin.' );
$order->save();

Plugins that touch orders should also declare whether they support HPOS, so WooCommerce can warn shop owners about incompatible ones:

PHP
<?php
add_action( 'before_woocommerce_init', function () {
    if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
            'custom_order_tables',
            __FILE__,
            true
        );
    }
} );

Only declare compatibility after you have made sure the plugin uses the order API everywhere.

Order statuses

An order moves through a small set of statuses. The most common are pending (waiting for payment), processing (paid, waiting to be fulfilled), on-hold, completed, cancelled, refunded and failed. In the database some storage layouts keep them with a wc- prefix (wc-processing), but the order methods give you the bare name. Changing the status with $order->update_status( 'completed' ) fires status hooks, so other code (emails, stock, your own plugin) can react.

flowchart LR
    A["Product page"] --> B["Cart"]
    B --> C["Checkout"]
    C --> D["Order created<br/>status: pending"]
    D --> E["Payment received<br/>status: processing"]
    E --> F["Shipped<br/>status: completed"]
    D --> G["Payment failed<br/>status: failed"]

A simplified order journey: each status change fires hooks that emails, stock handling and your code can use.

The cart and checkout flow

The cart lives in a session tied to a cookie, so each visitor has a private cart even when logged out. Code reaches it through WC()->cart:

PHP
<?php
WC()->cart->add_to_cart( 123, 2 );          // Product ID, quantity.
echo WC()->cart->get_cart_contents_count(); // Number of items.
echo WC()->cart->get_total();               // Formatted total.
WC()->cart->empty_cart();

Totals are calculated every time the cart changes: line subtotals, coupons, fees, shipping and taxes are combined into the final amount. At checkout the customer enters billing and shipping details, picks a shipping method and a payment gateway, and WooCommerce validates everything, creates the order, hands off to the gateway and finally shows the "thank you" page.

Two consequences matter for performance. First, cart, checkout and "My account" pages are personal, so page caches and CDNs must not cache them; WooCommerce sets cookies and cache-control headers that good caching plugins respect. Second, a shop has far more writes than a blog, so object caching and database health matter more (see caching and WP-Cron).

A totals calculator you can run

The first stand-in shows why shops store money as integers. It works in cents, applies a percentage coupon, adds shipping that is free over a threshold, and adds tax on the discounted goods. Floating-point arithmetic is avoided on purpose: 0.1 + 0.2 is not exactly 0.3, and a shop that adds floats will eventually be one cent off.

PHP Cart totals in integer cents (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.

Real WooCommerce works with decimals and a configurable number of decimal places and rounding rules, and it can show prices with or without tax. The lesson is the same: do not compute money with naive float arithmetic in your own code, and always format with wc_price() for display.

Hooks you will meet first

WooCommerce has hundreds of hooks. A few of them cover most customizations:

Hook Type When it runs
woocommerce_before_add_to_cart_button action Just before the "Add to cart" button on a product page
woocommerce_after_add_to_cart_button action Just after that button
woocommerce_add_to_cart_validation filter Lets you reject adding an item (return false)
woocommerce_product_get_price filter Changes the price a product reports
woocommerce_cart_calculate_fees action Add extra fees while totals are calculated
woocommerce_checkout_process action During checkout validation, add errors here
woocommerce_payment_complete action After a payment is confirmed
woocommerce_order_status_completed action An order has moved to completed
woocommerce_thankyou action On the order confirmation page

Here is a typical real example, read-only: add a gift-wrap option to the product page and a fee to the cart. It shows the hook pattern from actions and filters applied to a shop.

PHP
<?php
add_action( 'woocommerce_before_add_to_cart_button', function () {
    echo '<label class="acme-gift">';
    echo '<input type="checkbox" name="acme_gift_wrap" value="1"> ';
    echo esc_html__( 'Add gift wrap (+$3.00)', 'acme-shop' );
    echo '</label>';
} );

add_filter( 'woocommerce_add_cart_item_data', function ( array $data ): array {
    // The nonce for the add-to-cart form is checked by WooCommerce itself.
    if ( ! empty( $_POST['acme_gift_wrap'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
        $data['acme_gift_wrap'] = true;
    }
    return $data;
} );

add_action( 'woocommerce_cart_calculate_fees', function ( WC_Cart $cart ) {
    foreach ( $cart->get_cart() as $item ) {
        if ( ! empty( $item['acme_gift_wrap'] ) ) {
            $cart->add_fee( __( 'Gift wrap', 'acme-shop' ), 3.00 );
            return;
        }
    }
} );

Notice that the fee is added only once, however many items request it. Think about edge cases like that before you ship.

An order lifecycle with hooks (stand-in)

The second stand-in is a tiny hook system plus an order that only allows sensible status changes. When the status changes, a hook named after the new status fires, which is how plugins react to "order completed" in the real thing.

PHP Order statuses and status hooks (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.

The first attempt to jump straight from pending to completed is refused, so no email goes out. Real WooCommerce is more permissive than this stand-in (an admin can set almost any status), but the hook-per-status design is the same.

Template overrides

WooCommerce draws shop pages from template files inside the plugin, for example templates/single-product/add-to-cart/simple.php. To change the markup you do not edit the plugin. You copy the file into your theme in a woocommerce folder, keeping the same path:

TEXT
wp-content/themes/my-theme/woocommerce/single-product/add-to-cart/simple.php

WooCommerce checks the theme first and uses your copy when it exists. The catch is maintenance: a copied template does not receive plugin updates, so it can fall behind. Each core template carries an @version comment, and the WooCommerce, Status screen in wp-admin lists overrides that are outdated. Prefer a hook when one exists at the spot you need, and override a template only for structural changes. Block themes use WooCommerce blocks and block templates instead, edited in the Site Editor (see block templates and template parts).

Extending WooCommerce safely

  • Check that WooCommerce is active before calling its functions, for example with class_exists( 'WooCommerce' ) inside a hook such as plugins_loaded, or by hooking into woocommerce_loaded.
  • Use the CRUD objects and functions (wc_get_product(), wc_get_order(), setters plus save()), never raw SQL or meta keys for products and orders.
  • Declare HPOS compatibility only when it is true, and test with HPOS on.
  • Prefer hooks to template overrides and keep overrides small.
  • Prefix everything (functions, meta keys, option names) as in your first plugin, and escape output as in escaping output.
  • Test the whole flow on a staging copy: add to cart, checkout with the test gateway, check emails and stock.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How should plugin code read order data so it keeps working with High-Performance Order Storage?

    With HPOS, orders no longer live in the posts tables. The order object and WooCommerce's order functions work with either storage layout.
  2. 2. Why does a shop store money as integers (or fixed decimals) instead of plain floats?

    Binary floats cannot represent many decimal fractions exactly, so 0.1 + 0.2 is not exactly 0.3. Small errors add up across a cart.
  3. 3. What is the safest way to change the HTML of the add-to-cart area when a hook exists there?

    Edits inside a plugin are lost on update. A hook keeps your change separate and survives updates, and a template override is the fallback when no hook fits.
  4. 4. Why should cart and checkout pages not be cached for everyone?

    A cart belongs to one visitor and changes constantly. Serving one visitor's cached cart to another would be a serious bug.

Summary

  • WooCommerce is a plugin built on WordPress features: a product post type, taxonomies, options, hooks and its own tables.
  • Get products with wc_get_product() and orders with wc_get_order(); change them with setters and save().
  • HPOS stores orders in dedicated tables, so never use post meta functions or WP_Query for orders, and declare compatibility honestly.
  • The cart lives in a session; totals combine line prices, coupons, fees, shipping and tax, and money should never be added as floats.
  • Order status changes fire hooks that emails, stock handling and your code can use.
  • Prefer hooks to template overrides, keep overrides small and watch their @version.
  • The runnable code is a plain-PHP stand-in, not real WooCommerce.

Next: Testing, Coding Standards and Deployment