Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Cart and Pricing

The Cart and Session

Understand WC_Cart and WC_Session_Handler: cart item keys, custom cart item data, add-to-cart validation, fees, notices, persistent carts and caching pitfalls.

The cart is where a browsing visitor becomes a buyer, and it is where most custom WooCommerce features first touch the shopping flow: a gift message, a custom engraving, a minimum order quantity, a handling fee. All of them hook into the same two objects. WC_Cart holds the lines the shopper wants to buy and calculates totals. WC_Session_Handler remembers that cart between page loads, even for visitors who never log in.

This lesson explains how a cart line is identified, how to attach your own data to it, where to validate before something enters the cart, and how fees and notices work. It ends with the pitfalls that make carts look wrong on cached pages. Product basics are in Working With Products in Code; the general design ideas behind carts are in Cart Design. The WooCommerce code below is read-only, because the site cannot run WordPress. The two stand-ins are plain PHP that mimic the key ideas, and each says what is real and what is simplified.

The cart is a list of keyed lines

You reach the cart through the main object: WC()->cart. Each line has a cart item key, a string (an MD5 hash) that identifies the line. The array you get from WC()->cart->get_cart() is indexed by these keys, and each entry holds the product ID, the variation ID, the quantity, the product object and any extra data.

PHP
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    $product  = $cart_item['data'];       // WC_Product object
    $quantity = $cart_item['quantity'];
    $price    = $product->get_price();
}

Adding a product is one call:

PHP
$key = WC()->cart->add_to_cart(
    $product_id,
    2,                       // quantity
    0,                       // variation ID (0 for non-variable products)
    [],                      // variation attributes
    [ 'engraving' => 'AB' ]  // your own cart item data
);

if ( false === $key ) {
    // Validation failed; a notice was added explaining why.
}

add_to_cart() returns the line's key, or false when something refused the item. The key is built from the product ID, the variation ID, the variation attributes and your cart item data. That has an important consequence: adding the same product twice with identical data increases the quantity of one line; adding it with different data creates a second line. That is how a shopper can have two engraved mugs with different texts in the cart, and two plain mugs as one line with quantity 2.

flowchart LR
    A["add_to_cart(product, qty, data)"] --> B["woocommerce_add_to_cart_validation<br/>(filter, can refuse)"]
    B --> C["woocommerce_add_cart_item_data<br/>(filter, attach data)"]
    C --> D["Build item key<br/>from product + data"]
    D --> E{"Key already<br/>in cart?"}
    E -->|yes| F["Add to quantity"]
    E -->|no| G["Insert new line"]
    F --> H["woocommerce_add_to_cart<br/>(action)"]
    G --> H

The path of an add-to-cart request: validation, data, key, then merge or insert.

A stand-in for keys and merging

The first TryIt rebuilds this idea in a few lines. The real key function is internal to WooCommerce, and you should never depend on its exact format; what matters is the behaviour: same inputs give the same key, any difference in data gives a new key.

PHP Cart item keys and merging lines (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: lines are keyed by a hash of product and data, and equal keys merge. What is the stand-in: WooCommerce also hashes the variation ID and attributes, and the cart stores a product object in each line, not just an ID.

Attaching your own data to a line

To record something about this purchase of the product, for example an engraving, use cart item data. It travels with the line through the whole flow, and the standard pattern uses four hooks, one for each step.

PHP
// 1. Capture the posted value when the item is added.
add_filter( 'woocommerce_add_cart_item_data', function ( array $cart_item_data, int $product_id ): array {
    if ( isset( $_POST['acme_engraving'] ) && '' !== $_POST['acme_engraving'] ) {
        $text = sanitize_text_field( wp_unslash( $_POST['acme_engraving'] ) );
        $cart_item_data['acme_engraving'] = mb_substr( $text, 0, 20 );
    }
    return $cart_item_data;
}, 10, 2 );

// 2. Show it in the cart and at checkout.
add_filter( 'woocommerce_get_item_data', function ( array $item_data, array $cart_item ): array {
    if ( ! empty( $cart_item['acme_engraving'] ) ) {
        $item_data[] = [
            'key'   => __( 'Engraving', 'acme-extras' ),
            'value' => $cart_item['acme_engraving'],
        ];
    }
    return $item_data;
}, 10, 2 );

// 3. Copy it to the order line when the order is created.
add_action( 'woocommerce_checkout_create_order_line_item', function ( $item, string $cart_item_key, array $values ): void {
    if ( ! empty( $values['acme_engraving'] ) ) {
        $item->add_meta_data( __( 'Engraving', 'acme-extras' ), $values['acme_engraving'] );
    }
}, 10, 3 );

Step 1 is also where you make lines unique when needed. If two additions of the same product must never merge (say, every gift card is distinct), add a unique value to the data, such as $cart_item_data['unique_key'] = uniqid( '', true );. The key function then produces a different key every time.

Always sanitize on the way in and escape on the way out. The value in $_POST is untrusted, and cart item data is stored in the session and later written to the order. WooCommerce escapes get_item_data values when it prints them, but if you echo your own data in a template you must escape it yourself. See Security for WooCommerce Extensions for the full checklist.

Cart item data is restored from the session on every request. If you store large or non-scalar values in it, the session grows and each page load pays for it. Keep it small: IDs, short strings and numbers, never entire objects.

Validating before the item enters the cart

woocommerce_add_to_cart_validation is a filter that receives $passed (true by default), the product ID, the quantity and, for variable products, the variation details. Return false to block the addition, and explain why with a notice.

PHP
add_filter( 'woocommerce_add_to_cart_validation', function ( bool $passed, int $product_id, int $quantity ): bool {
    $min = (int) get_post_meta( $product_id, '_acme_min_qty', true );

    if ( $min > 1 && $quantity < $min ) {
        wc_add_notice(
            sprintf(
                /* translators: %d: minimum quantity */
                __( 'This product requires a minimum quantity of %d.', 'acme-extras' ),
                $min
            ),
            'error'
        );
        return false;
    }

    return $passed;
}, 10, 3 );

Two habits keep this robust. First, return $passed unchanged when your rule does not apply, so you never turn another plugin's false into true. Second, remember that validation runs on the add-to-cart request only. Quantities can also change on the cart page, so cart-level rules need a second check on woocommerce_check_cart_items, and checkout rules on woocommerce_checkout_process. A rule enforced in one place only is a rule that can be bypassed.

wc_add_notice( $message, $type ) stores a message in the session so the next page (or an AJAX response) can show it. The types are 'success', 'error' and 'notice'. An 'error' notice at checkout also stops the order from being placed.

Fees

A fee is an extra line in the totals that is not tied to a product: handling, a gift wrap charge, a payment surcharge. Add it on woocommerce_cart_calculate_fees, which runs every time totals are recalculated.

PHP
add_action( 'woocommerce_cart_calculate_fees', function ( WC_Cart $cart ): void {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
        return;
    }

    $wrap_count = 0;
    foreach ( $cart->get_cart() as $line ) {
        if ( ! empty( $line['acme_gift_wrap'] ) ) {
            $wrap_count += $line['quantity'];
        }
    }

    if ( $wrap_count > 0 ) {
        $cart->add_fee( __( 'Gift wrap', 'acme-extras' ), 2.50 * $wrap_count, true );
    }
} );

The arguments of add_fee( $name, $amount, $taxable = false, $tax_class = '' ) matter: a fee is not taxed unless you pass true. Because the hook runs on every recalculation, never save the fee anywhere yourself; compute it from the current cart each time and it stays correct when quantities change. Pricing logic in more depth, including product price changes, follows in Dynamic Pricing, Fees and Discounts, and the money rules (integer cents, rounding) are in Money as Integers.

A stand-in for validation, fees and notices

The second TryIt puts validation, notices and a fee together. It mimics the flow only: the filter chain is a list of callbacks, and notices are collected in an array just as wc_add_notice() collects them in the session. Amounts are integer cents.

PHP Validation, notices and a fee (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: validators chain and each must return the incoming result when it does not apply, notices are collected and shown later, and fees are derived from the current lines. What is the stand-in: WooCommerce passes more arguments to its filters, stores notices in the session and renders them as templates.

Where the cart lives: the session

Logged-in customers and guests both have carts, so WooCommerce cannot rely on PHP's $_SESSION. Its own session handler (WC_Session_Handler, available as WC()->session) keeps the data in a database table and gives the browser a cookie whose name starts with wp_woocommerce_session_. The cookie holds a customer ID and an expiry time, not the cart; the cart is looked up in the table. The handler writes to the table at the end of the request if the data changed.

Two details matter for performance and privacy. First, WooCommerce starts a customer session for a guest only when it must, such as when something is added to the cart, which keeps ordinary page views cookie-free and cacheable. Second, the session table grows with every cart that is created; WooCommerce schedules cleanup of expired rows, but a busy shop should still watch its size (see Performance and Scaling Large Stores).

Use the session for short-lived state about the visit:

PHP
WC()->session->set( 'acme_referral_code', 'SPRING' );
$code = WC()->session->get( 'acme_referral_code', '' );

Do not use it for anything that must outlive the cart, such as a loyalty balance; that belongs in user meta or your own table.

Persistent carts add continuity for logged-in customers: WooCommerce saves the cart into user meta, so a shopper who logs in on another device sees the same lines. Guest carts are tied to the cookie and the session row. When a guest logs in, the guest cart is merged with the saved one.

Never read $_SESSION or call session_start() in a store extension. It breaks page caching, can lock sessions on parallel requests and ignores WooCommerce's own cart handling. Use WC()->session instead.

Fragments and caching pitfalls

A cached page cannot contain a personal cart count. WooCommerce solves this with cart fragments: a script requests the current mini-cart HTML through an AJAX endpoint (?wc-ajax=get_refreshed_fragments) and swaps it into the page. Your own cart-dependent widgets can join in with the woocommerce_add_to_cart_fragments filter, which maps a CSS selector to replacement HTML.

PHP
add_filter( 'woocommerce_add_to_cart_fragments', function ( array $fragments ): array {
    ob_start();
    echo '<span class="acme-count">' . (int) WC()->cart->get_cart_contents_count() . '</span>';
    $fragments['span.acme-count'] = ob_get_clean();
    return $fragments;
} );

Common pitfalls:

  • Printing cart data into cacheable HTML. If a full-page cache stores your template with the shopper's cart count inside, the next visitor sees it. Load it with a fragment or an API call instead, the same rule as the rest of this site's design.
  • Cart, checkout and account pages must be excluded from page caching. Most hosts do this by default for the WooCommerce pages; check a custom setup.
  • Expensive work in woocommerce_cart_calculate_fees or price hooks. They run on every recalculation, which can be several times per request. Cache lookups and avoid database queries inside loops.
  • Assuming the cart exists. In admin screens, REST requests and cron, WC()->cart may be null or not loaded. Guard with if ( ! WC()->cart ) { return; } and avoid touching the cart outside storefront requests.
  • Trusting posted prices. Keep prices on the server. Compute them from the product, never from a hidden field. This is the subject of the security lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A customer adds product 10 twice, both times with the same engraving text. What happens to the cart?

    The cart item key is built from the product and the cart item data. Identical inputs give the same key, so the quantity of the existing line increases.
  2. 2. Which return value tells you that add_to_cart() refused an item?

    add_to_cart() returns the cart item key on success and false when validation or another check refuses the item.
  3. 3. Your validation callback on woocommerce_add_to_cart_validation does not apply to the current product. What should it return?

    Returning $passed keeps the result of other callbacks. Returning true could override another plugin's refusal.
  4. 4. When is a fee added with add_fee() taxed?

    The third argument of add_fee() defaults to false, so a fee is untaxed unless you pass true (and optionally a tax class).
  5. 5. Why should a theme or plugin avoid session_start() in a WooCommerce shop?

    WooCommerce manages its own database-backed session. Native PHP sessions add cookies to every page, defeat caching and can lock parallel requests.

Summary

  • WC()->cart holds keyed lines; the key comes from the product, the variation and your cart item data, so identical additions merge and different data makes a new line.
  • Attach per-purchase data with woocommerce_add_cart_item_data, show it with woocommerce_get_item_data and copy it to the order with woocommerce_checkout_create_order_line_item.
  • Validate on woocommerce_add_to_cart_validation, return $passed when your rule does not apply, and explain refusals with wc_add_notice().
  • Add fees on woocommerce_cart_calculate_fees, compute them from the current cart each time, and pass true when the fee is taxable.
  • WC()->session stores the cart in a database table behind a cookie; keep session data small and never use $_SESSION.
  • Keep personal cart data out of cached HTML and use fragments or API calls to show it.

Next: Dynamic Pricing, Fees and Discounts