Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Quality and Production

Security for WooCommerce Extensions

Secure your WooCommerce extension: capability checks, nonces, escaping, wc_clean, safe SQL, price tampering, uploads, abuse limits and privacy exporters.

A store handles money, addresses, phone numbers and purchase history. A bug in your extension is not just a glitch: it can let a stranger change a price, read another customer's order, or run code on the server. Security is therefore part of the feature, not a polish step.

This lesson applies the general rules from WordPress Security Hardening to the places where WooCommerce plugins most often go wrong. It adds the store-specific risks: the price is never the browser's to decide, order data is private, and abuse of cheap endpoints (coupons, carts) costs real money. The real code needs WordPress, so those snippets are read-only. The TryIts are runnable PHP stand-ins that show the logic. For the shop-wide view, see Shop Security.

The four questions for every entry point

Every place where outside data enters your code (a form post, an AJAX call, a REST route, a webhook, a URL parameter) needs four answers:

  1. Who is asking? Authentication is handled by WordPress; you ask is_user_logged_in() or get_current_user_id().
  2. Are they allowed? A capability check. Not "is this an admin page" but current_user_can().
  3. Did they mean to do it? A nonce for browser actions, which defends against cross-site request forgery.
  4. Is the data valid? Sanitize input on the way in, escape output on the way out, and use prepared statements for SQL.
flowchart LR
  R["Request"] --> A["Capability check"]
  A --> N["Nonce or token check"]
  N --> V["Validate and sanitize"]
  V --> L["Business logic<br/>server-side prices"]
  L --> O["Escape on output"]

Each layer catches a different kind of mistake; skipping one leaves a gap the others do not cover.

Capabilities: manage_woocommerce and friends

WooCommerce defines its own capabilities. The most important is manage_woocommerce, held by the Shop Manager and Administrator roles. Use it for store settings and order-management actions. Use edit_shop_orders and similar order capabilities when you act on a specific order, and edit_product/edit_products for product data. Do not use manage_options for store features: it excludes shop managers and is the wrong meaning.

PHP
<?php
add_action( 'admin_post_acme_export_orders', function () {
    if ( ! current_user_can( 'manage_woocommerce' ) ) {
        wp_die( esc_html__( 'You are not allowed to do this.', 'acme' ), 403 );
    }
    check_admin_referer( 'acme_export_orders' ); // nonce

    $status = isset( $_POST['status'] ) ? wc_clean( wp_unslash( $_POST['status'] ) ) : 'any';
    // ... build the export
} );

Two habits matter here. First, the check is per action, not per page: hiding a button is not security, because anyone can send the request by hand. Second, object-level checks: if the request carries an order ID, make sure this user may see that order. A logged-in customer must only reach their own orders ($order->get_customer_id() === get_current_user_id()), otherwise changing the ID in the URL reads someone else's data. This is called an insecure direct object reference, and it is one of the most common real-world bugs.

Nonces, sanitizing and escaping

A nonce is a short-lived token tied to the user and an action name. wp_nonce_field() and wp_create_nonce() create it; check_admin_referer(), check_ajax_referer() or wp_verify_nonce() verify it. A nonce proves intent, not permission: always do the capability check too.

For cleaning input, WooCommerce gives you wc_clean(), which runs sanitize_text_field() over strings and recurses into arrays. Remember wp_unslash() first, because WordPress adds slashes to superglobals. Pick a sanitizer for the data type:

  • text: wc_clean() or sanitize_text_field()
  • rich text: wp_kses_post()
  • numbers: absint(), or wc_format_decimal() for prices
  • email: sanitize_email(); URL: esc_url_raw()

On output, escape late, for the context: esc_html(), esc_attr(), esc_url(), wp_kses_post(). Order data (billing names, notes, a customer's free-text field) is user-controlled and must be escaped like any other input, even in the admin. Stored cross-site scripting through an order note is a classic attack, because a shop manager with high privileges is the one who views it.

SQL and order data

Use the CRUD classes (CRUD Classes and Data Stores) and wc_get_orders() wherever you can. They handle storage differences such as HPOS and escape values for you. When you must write SQL, use $wpdb->prepare() with placeholders and never put a variable into the string:

PHP
<?php
global $wpdb;
$table = $wpdb->prefix . 'acme_points';

// Wrong: user input inside the query.
$rows = $wpdb->get_results( "SELECT * FROM $table WHERE customer_id = " . $_GET['id'] );

// Right: placeholders and the right type.
$rows = $wpdb->get_results(
    $wpdb->prepare( "SELECT * FROM {$table} WHERE customer_id = %d AND status = %s", absint( $_GET['id'] ?? 0 ), 'active' )
);

For lists, build the right number of %d placeholders with implode( ',', array_fill( 0, count( $ids ), '%d' ) ) and pass the IDs to prepare().

Price tampering: the server decides

Never trust a price, total, discount or "is paid" flag sent by the browser. A hidden field called price can be edited in the developer tools in seconds. The only trustworthy sources are your own database and calculation: look up the product by ID, compute the price on the server, and ignore any price in the request.

The same goes for quantity (reject zero, negatives and fractions unless the product allows them), for coupon codes (validate on the server), and for the amount in a payment notification: compare the amount the provider says it captured with the order total before marking an order paid. See Webhooks, Signatures and Payment Security.

PHP Price tampering: trusting the client versus the catalog

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 "unsafe" column charges 2 cents for two notebooks and gives a negative total for a refund-like line. The safe version ignores the posted price entirely.

Uploads, abuse and the second layer

File uploads. If you accept files (custom product images, proof of payment), use wp_handle_upload() with an explicit MIME allow-list, limit the size, and never trust the file name or the browser's content type. Do not store uploads in a place where the server would execute them as PHP. WooCommerce keeps its own downloadable files in a protected folder for this reason.

Rate limiting. Endpoints that are cheap for an attacker and valuable to them, such as coupon validation (guessing codes), login, "apply gift card", or order lookups, need a throttle. Count attempts per IP or per session in a transient and stop after a small number. A coupon form with no limit is a free brute-force oracle.

PHP A simple attempt limiter for coupon guessing

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.

Even the valid code at t=12 is blocked: the limiter does not know the guess would have worked, which is what stops a brute-force run. After the window passes (t=70) the shopper can try again.

Privacy: exporters and erasers

If your plugin stores personal data (names, addresses, points tied to a user), the law in many regions gives people the right to export and delete it. WordPress has a personal-data tool, and your plugin joins it with two filters: wp_privacy_personal_data_exporters to add an exporter callback, and wp_privacy_personal_data_erasers to add an eraser callback. Each receives an email address and a page number, so you can process large data sets in pages, and returns the data or the count of items removed. Order data that the law requires you to keep (for tax records) may be anonymized rather than deleted; WooCommerce does the same with its own privacy settings. Also avoid logging more than you need: no card numbers, no full addresses, no secrets in wc_get_logger() output. See Privacy and Compliance.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which capability is the right default for a store-management admin action?

    manage_woocommerce is held by shop managers and administrators and describes store management. manage_options excludes shop managers.
  2. 2. Does a valid nonce prove the user is allowed to perform the action?

    A nonce defends against forged requests. Authorization is a separate question answered by current_user_can() and object-level checks.
  3. 3. A checkout form posts a hidden field called price. What should the server do with it?

    Anything in the request can be edited. The catalog is the single source of truth for prices.
  4. 4. What is an insecure direct object reference in a store plugin?

    Without an ownership check, a logged-in user can substitute another ID and read or change data that is not theirs.

Summary

  • Ask four questions at every entry point: who, allowed, intended, valid.
  • Use manage_woocommerce (or object capabilities) for store actions; add object-level ownership checks for customer data.
  • Nonces prove intent, not permission; sanitize input with wc_clean() and friends, escape output for its context.
  • Prefer CRUD classes; use $wpdb->prepare() for any raw SQL.
  • Never trust prices, totals or paid flags from the client; recompute on the server and compare payment amounts.
  • Limit uploads and throttle guessable endpoints; wire up privacy exporters and erasers when you store personal data.

Next: Testing WooCommerce Code