Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Practice and Review

Exercises With Solutions

Twelve WooCommerce plugin exercises on hooks, CRUD, cart, pricing, coupons, orders, gateways, shipping and REST, with worked solutions and runnable PHP checks.

Reading about WooCommerce is not the same as writing it. This lesson gives you twelve small exercises, one for each big idea in the track: hooks, the CRUD layer, the cart, pricing, coupons, orders, gateways, shipping, REST and security. Each exercise has a task, a hint and a worked solution.

WooCommerce itself cannot run on this site, so the solutions are read-only snippets written against the real API, and three runnable TryIt blocks check the underlying logic (hook ordering, cart keys, tier prices, status rules, shipping rates, signatures, pagination) in plain PHP. Those stand-ins are not WooCommerce code; they show why the real code behaves as it does. Try each exercise on paper or in your own development site before opening the solution. Setup help is in Development Environment and Tooling.

flowchart LR
    A["Hooks<br/>1 to 2"] --> B["CRUD and cart<br/>3 to 5"]
    B --> C["Pricing and coupons<br/>5 to 6"]
    C --> D["Orders and payments<br/>7 to 8, 11"]
    D --> E["Shipping and REST<br/>9 to 10, 12"]

The exercises follow the order of the track.

Part 1: Hooks

Exercise 1: Print a notice above the add-to-cart button

Task. On single product pages, show the text "Ships within 2 working days" just above the add-to-cart button, for every product type.

Hint. Look for a woocommerce_before_* action in the add-to-cart templates. See The WooCommerce Hook Map. Always escape output.

Solution (read-only).

PHP
add_action( 'woocommerce_before_add_to_cart_button', function (): void {
    echo '<p class="acme-shipping-note">'
        . esc_html__( 'Ships within 2 working days', 'acme' )
        . '</p>';
} );

The hook runs inside the add-to-cart form for simple and variable products alike. A hook is better than copying a template, because the template can stay updatable.

Exercise 2: Remove the result count from the shop page

Task. Remove the "Showing 1 to 12 of 40 results" line from the product archive without editing core files.

Hint. Find which callback prints it, on which hook and with which priority. remove_action() only works with the same hook, callback and priority, and only after the callback has been added.

Solution (read-only).

PHP
add_action( 'init', function (): void {
    remove_action( 'woocommerce_before_shop_loop', 'woocommerce_result_count', 20 );
} );

You can confirm the priority by searching the WooCommerce source for woocommerce_result_count. Removing in init is a common safe point, because the default hooks are registered when WooCommerce loads. Use CSS only as a last resort; hiding does not stop the work from being done.

Run the first logic check now. It uses a tiny hook dispatcher, a cart item key builder and a tier price function, so it also covers exercises 4 and 5.

PHP Hooks, cart keys and tier prices

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.

Part 2: CRUD and the cart

Exercise 3: Update a price by SKU

Task. Write a function that sets the regular price of the product with a given SKU. It must do nothing (and not crash) if the SKU does not exist.

Hint. Use the CRUD getters and setters, not update_post_meta(). See Working With Products in Code and CRUD Classes and Data Stores.

Solution (read-only).

PHP
function acme_set_price_by_sku( string $sku, string $price ): bool {
    $product_id = wc_get_product_id_by_sku( $sku );
    if ( ! $product_id ) {
        return false;
    }

    $product = wc_get_product( $product_id );
    if ( ! $product ) {
        return false;
    }

    $product->set_regular_price( wc_format_decimal( $price ) );
    $product->save();   // writes only what changed and clears the right caches

    return true;
}

save() also lets WooCommerce sync lookup tables and fire its hooks. Writing meta directly skips all of that, and the shop can show stale prices.

Exercise 4: Two engravings must be two cart lines

Task. A product accepts an engraving text from a form field named engraving. Adding the same product with different texts must create different cart lines; the same text must merge.

Hint. Cart lines are identified by a key built from the product, variation and cart item data. Add your data in the filter that builds that data. Validate first.

Solution (read-only).

PHP
add_filter( 'woocommerce_add_to_cart_validation', function ( $passed, $product_id ) {
    if ( isset( $_POST['engraving'] ) && mb_strlen( wp_unslash( $_POST['engraving'] ) ) > 20 ) {
        wc_add_notice( __( 'Engraving can have at most 20 characters.', 'acme' ), 'error' );
        return false;
    }
    return $passed;
}, 10, 2 );

add_filter( 'woocommerce_add_cart_item_data', function ( array $data ) {
    if ( ! empty( $_POST['engraving'] ) ) {
        $data['acme_engraving'] = sanitize_text_field( wp_unslash( $_POST['engraving'] ) );
    }
    return $data;
} );

(In production, also verify a nonce or use the Store API, see The Cart and Session.) The first TryIt above shows the idea of the key: change one piece of data and the hash, and so the line, changes.

Exercise 5: 10% off from ten pieces

Task. For a product, give a 10% unit discount when the quantity is 10 or more, without changing the stored product price.

Hint. Recalculate in woocommerce_before_calculate_totals and set the price on the cart item's product object. Do the maths from the original price every time, so the discount never stacks. Money is safest as integer cents (see Dynamic Pricing, Fees and Discounts).

Solution (read-only).

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

    foreach ( $cart->get_cart() as $item ) {
        $product = $item['data'];
        $base    = (float) $product->get_regular_price();

        if ( $item['quantity'] >= 10 ) {
            $product->set_price( round( $base * 0.9, wc_get_price_decimals() ) );
        } else {
            $product->set_price( $base );
        }
    }
} );

The TryIt above computes the same idea in cents. Rounding half up with integers avoids float surprises.

Part 3: Coupons and orders

Exercise 6: A one-use welcome coupon

Task. Create a coupon WELCOME10 in code: 10% off, usable once in total, expiring on a fixed date.

Hint. The CRUD class for coupons is WC_Coupon. Make the function idempotent, otherwise running it twice creates duplicates. See Coupons in Code.

Solution (read-only).

PHP
function acme_create_welcome_coupon(): int {
    $existing = wc_get_coupon_id_by_code( 'WELCOME10' );
    if ( $existing ) {
        return $existing;
    }

    $coupon = new WC_Coupon();
    $coupon->set_code( 'WELCOME10' );
    $coupon->set_discount_type( 'percent' );
    $coupon->set_amount( 10 );
    $coupon->set_usage_limit( 1 );
    $coupon->set_date_expires( '2030-12-31' );

    return $coupon->save();
}

Exercise 7: Complete paid virtual orders automatically

Task. When an order moves to processing, and every item is virtual and downloadable, move it to completed and add a note. Never touch other orders.

Hint. Use the status hook, check each item, and let WooCommerce do the transition so emails and stock logic still run. See Order Statuses and the Order Lifecycle.

Solution (read-only).

PHP
add_action( 'woocommerce_order_status_processing', function ( int $order_id ): void {
    $order = wc_get_order( $order_id );
    if ( ! $order ) {
        return;
    }

    foreach ( $order->get_items() as $item ) {
        $product = $item->get_product();
        if ( ! $product || ! $product->is_virtual() || ! $product->is_downloadable() ) {
            return;
        }
    }

    $order->update_status( 'completed', __( 'Auto-completed: digital items only.', 'acme' ) );
} );

Never read order data with get_post_meta(). Under HPOS the order is not a post. Use the order object (see Orders and High-Performance Order Storage).

Part 4: Gateways and shipping

Exercise 8: Make the charge safe to retry

Task. Your gateway's process_payment() calls a provider. A shopper double-clicks "Place order". Make sure one order never causes two charges.

Hint. Send an idempotency key derived from something stable, such as the order ID and total. Mark the order paid only on a confirmed result. See Building a Payment Gateway.

Solution (read-only).

PHP
public function process_payment( $order_id ) {
    $order = wc_get_order( $order_id );
    $key   = hash( 'sha256', 'order-' . $order->get_id() . '-' . $order->get_total() );

    $result = $this->api->charge( [
        'amount'   => (int) round( $order->get_total() * 100 ),
        'currency' => $order->get_currency(),
    ], $key );

    if ( ! empty( $result['paid'] ) ) {
        $order->payment_complete( $result['id'] );
        return [ 'result' => 'success', 'redirect' => $this->get_return_url( $order ) ];
    }

    wc_add_notice( __( 'Payment failed, please try again.', 'acme' ), 'error' );
    return [ 'result' => 'failure' ];
}

The next TryIt simulates a provider that honors idempotency keys, plus exercises 7, 9, 10 and 11.

Exercise 9: A weight-based shipping rate

Task. Charge 5.00 for up to 1 kg and 1.50 for every further started kilogram; shipping is free above 100.00 of goods. Return the cost in cents.

Hint. In a WC_Shipping_Method the maths happens in calculate_shipping() and ends with add_rate(). See Custom Shipping Methods.

Solution (read-only).

PHP
public function calculate_shipping( $package = [] ) {
    $weight = 0.0;
    foreach ( $package['contents'] as $item ) {
        $weight += (float) $item['data']->get_weight() * $item['quantity'];
    }

    $cost = 5.00 + max( 0, ceil( $weight ) - 1 ) * 1.50;

    if ( $package['contents_cost'] >= 100 ) {
        $cost = 0.0;
    }

    $this->add_rate( [
        'id'    => $this->get_rate_id(),
        'label' => $this->title,
        'cost'  => $cost,
    ] );
}

Part 5: REST, security and HPOS

Exercise 10: A paginated, protected endpoint

Task. Expose GET /acme/v1/low-stock for shop managers only. It returns products with stock at or below a threshold, 20 per page, with total counts in headers.

Hint. Every REST route needs a real permission_callback. See Custom REST Endpoints and Outgoing Webhooks.

Solution (read-only).

PHP
add_action( 'rest_api_init', function (): void {
    register_rest_route( 'acme/v1', '/low-stock', [
        'methods'             => 'GET',
        'permission_callback' => fn() => current_user_can( 'manage_woocommerce' ),
        'args'                => [
            'page'      => [ 'default' => 1, 'sanitize_callback' => 'absint' ],
            'threshold' => [ 'default' => 5, 'sanitize_callback' => 'absint' ],
        ],
        'callback'            => function ( WP_REST_Request $request ) {
            $query = new WC_Product_Query( [
                'limit'        => 20,
                'paginate'     => true,
                'page'         => max( 1, $request['page'] ),
                'manage_stock' => true,
                'stock_status' => 'instock',
            ] );
            $found = $query->get_products();

            $rows = [];
            foreach ( $found->products as $product ) {
                if ( $product->get_stock_quantity() <= $request['threshold'] ) {
                    $rows[] = [ 'id' => $product->get_id(), 'stock' => $product->get_stock_quantity() ];
                }
            }

            $response = rest_ensure_response( $rows );
            $response->header( 'X-WP-Total', (string) $found->total );
            $response->header( 'X-WP-TotalPages', (string) $found->max_num_pages );
            return $response;
        },
    ] );
} );

Filtering by threshold after the query is simple but can be slow on huge catalogs; a real extension would filter in the query (see Performance and Scaling Large Stores).

Exercise 11: Verify an incoming webhook

Task. Verify that a request really came from the sender, using a shared secret and the raw body.

Hint. The signature is an HMAC of the raw body, not of parsed JSON. Compare in constant time. WooCommerce sends its own webhook signature as a base64-encoded HMAC-SHA256 in the X-WC-Webhook-Signature header. See Webhooks, Signatures and Payment Security and Webhooks and Signatures.

Solution (read-only).

PHP
function acme_verify_signature( string $raw_body, string $header, string $secret ): bool {
    $expected = base64_encode( hash_hmac( 'sha256', $raw_body, $secret, true ) );
    return hash_equals( $expected, $header );
}

$raw = file_get_contents( 'php://input' );
if ( ! acme_verify_signature( $raw, $_SERVER['HTTP_X_WC_WEBHOOK_SIGNATURE'] ?? '', $secret ) ) {
    status_header( 401 );
    exit;
}
PHP Status rules, idempotent charge, shipping, signature and pagination

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.

Exercise 12: Make an old snippet HPOS-safe

Task. This legacy code reads an order's billing email and a custom field. Rewrite it so it works with High-Performance Order Storage, and declare compatibility.

PHP
$email = get_post_meta( $order_id, '_billing_email', true );
$gift  = get_post_meta( $order_id, '_acme_gift_note', true );

Hint. Orders are objects with getters and meta methods. The compatibility declaration belongs on before_woocommerce_init. See Orders and High-Performance Order Storage.

Solution (read-only).

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

$order = wc_get_order( $order_id );
if ( $order ) {
    $email = $order->get_billing_email();
    $gift  = $order->get_meta( '_acme_gift_note', true );
}

To write a field, use $order->update_meta_data( '_acme_gift_note', $value ); $order->save();.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why did the wrong-priority remove in the first TryIt not remove the result count?

    A callback is stored per hook and priority. If the priority differs, nothing matches and the function returns false.
  2. 2. What makes two cart lines of the same product separate lines?

    The key is a hash of what identifies a line. Adding custom data changes the hash, so the lines stay apart.
  3. 3. In the tier price exercise, why recompute from the regular price every time?

    The totals hook can run more than once per request. Starting from the stored price each time keeps the result stable.
  4. 4. Why use hash_equals() and the raw body when verifying a webhook?

    Even one extra space changes the HMAC. Constant-time comparison avoids leaking how many leading characters matched.
  5. 5. How should you read an order's billing email under HPOS?

    Under HPOS orders are not posts. The order object hides where data is stored.

Summary

  • Hooks are matched by hook name, callback and priority; remove with all three.
  • Use CRUD objects and save() instead of raw meta, and the order object instead of get_post_meta().
  • Cart lines are keyed by product, variation and item data; recalculate prices from the stored base price.
  • Make payments idempotent, verify webhooks over the raw body in constant time, and protect REST routes with real capability checks.
  • Do the money maths in integer cents and check boundaries (9 vs 10 pieces, exactly 100.00).

Next: WooCommerce Interview Questions