Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Practice and Review

WooCommerce Cheat Sheet

A quick WooCommerce developer reference: common functions, hooks, class map, CRUD patterns, order statuses, WP-CLI and debugging snippets, and the pitfalls to avoid.

This is a quick reference for everyday WooCommerce plugin work. It does not teach; it reminds. Each block links to the lesson that explains the idea. Real WooCommerce code is read-only here, since WooCommerce cannot run on this site. Two small runnable stand-ins at the end (a status transition table and a price rounding check) help you test your understanding in plain PHP. Names and signatures can change between WooCommerce versions, so confirm unusual ones in the source of the version you target.

flowchart LR
    R["Request"] --> W["WordPress<br/>hooks and options"]
    W --> C["WooCommerce<br/>CRUD, cart, checkout"]
    C --> S["Data stores<br/>posts or HPOS tables"]

Your code talks to CRUD objects and hooks, not to the tables.

Getting objects

PHP
$product = wc_get_product( $id );          // WC_Product or false
$order   = wc_get_order( $id );            // WC_Order, refund, or false
$coupon  = new WC_Coupon( 'WELCOME10' );   // by code or ID
$cart    = WC()->cart;                     // may be null in admin or REST
$customer = WC()->customer;
$session  = WC()->session;

$id = wc_get_product_id_by_sku( 'TSHIRT-RED' );
$id = wc_get_coupon_id_by_code( 'WELCOME10' );

Always test the result before calling methods on it.

Class map

Class Purpose
WooCommerce Main instance, returned by WC()
WC_Product, WC_Product_Simple, WC_Product_Variable, WC_Product_Variation Products
WC_Order, WC_Order_Item_Product, WC_Order_Refund Orders, lines, refunds
WC_Cart, WC_Customer, WC_Session_Handler Cart, customer, session
WC_Coupon Coupons
WC_Payment_Gateway Base for gateways
WC_Shipping_Method Base for shipping methods
WC_Email Base for emails
WC_Settings_Page Base for settings tabs
WC_Data, WC_Data_Store CRUD base and storage layer
WC_REST_Controller family REST v3 controllers

See How WooCommerce Is Built and CRUD Classes and Data Stores.

CRUD patterns

PHP
// Read
$name  = $product->get_name();
$price = $product->get_price();         // active price
$reg   = $product->get_regular_price();
$stock = $product->get_stock_quantity();

// Write: set, then save
$product->set_regular_price( '19.90' );
$product->set_manage_stock( true );
$product->set_stock_quantity( 25 );
$product->save();

// Create
$new = new WC_Product_Simple();
$new->set_name( 'Mug' );
$new->set_sku( 'MUG-01' );
$new->set_regular_price( '9.00' );
$id = $new->save();

// Custom data
$product->update_meta_data( '_acme_note', sanitize_text_field( $note ) );
$product->save();
$value = $product->get_meta( '_acme_note', true );

// Delete
$product->delete( true );   // true = permanently

Never use update_post_meta() or get_post_meta() for products' core fields or for orders. See Working With Products in Code.

Queries

PHP
$products = wc_get_products( [
    'status'   => 'publish',
    'limit'    => 20,
    'orderby'  => 'date',
    'order'    => 'DESC',
    'category' => [ 'shirts' ],
    'return'   => 'objects',   // or 'ids'
] );

$orders = wc_get_orders( [
    'status'     => [ 'processing', 'on-hold' ],
    'limit'      => 50,
    'date_created' => '>' . ( time() - DAY_IN_SECONDS ),
    'return'     => 'ids',
] );

Order statuses

Status Meaning
pending Order created, payment not received
failed Payment failed or was declined
on-hold Waiting for confirmation, such as a bank transfer
processing Paid, waiting to be fulfilled
completed Fulfilled
cancelled Cancelled by admin or customer
refunded Fully refunded
checkout-draft Draft order used by block checkout

In code, statuses are written without the wc- prefix when calling update_status(); the stored value in the database carries the prefix. Hooks follow the form woocommerce_order_status_{status} and woocommerce_order_status_{from}_to_{to}. See Order Statuses and the Order Lifecycle.

PHP
$order->update_status( 'completed', 'Shipped via courier.' );
$order->add_order_note( 'Customer called.', 0 );        // 0 = private note
$order->payment_complete( $transaction_id );

Common hooks

Goal Hook
Run after WooCommerce is loaded woocommerce_loaded, plugins_loaded (check class_exists)
Declare feature compatibility before_woocommerce_init
Content above add to cart woocommerce_before_add_to_cart_button
Validate add to cart woocommerce_add_to_cart_validation (filter)
Add cart item data woocommerce_add_cart_item_data (filter)
Change prices in cart woocommerce_before_calculate_totals
Add a fee woocommerce_cart_calculate_fees
Change checkout fields woocommerce_checkout_fields (filter)
Validate checkout (classic) woocommerce_checkout_process
Save checkout data woocommerce_checkout_create_order
Order paid woocommerce_payment_complete
Status changed woocommerce_order_status_changed
Register emails woocommerce_email_classes (filter)
Register gateways woocommerce_payment_gateways (filter)
Register shipping methods woocommerce_shipping_methods (filter)
Settings pages woocommerce_get_settings_pages (filter)
Product data panels woocommerce_product_data_tabs (filter), woocommerce_product_options_general_product_data
Save product fields woocommerce_admin_process_product_object

See The WooCommerce Hook Map.

Hook habits

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

add_filter( 'woocommerce_product_get_price', function ( $price, $product ) {
    return $price;   // always return
}, 10, 2 );

Match hook, callback and priority to remove a callback. Declare the number of accepted arguments with the fourth parameter of add_filter.

Templates

PHP
wc_get_template( 'myplugin/box.php', [ 'items' => $items ], '', plugin_dir_path( __FILE__ ) . 'templates/' );

Theme override path: yourtheme/woocommerce/. See Template Overrides and Plugin Templates.

Money and formatting

PHP
wc_price( 19.9 );                       // formatted, with currency symbol
wc_format_decimal( '19,90' );           // normalizes to a decimal string
wc_get_price_decimals();                // configured decimals
wc_get_price_including_tax( $product ); // uses tax settings
wc_get_price_excluding_tax( $product );
get_woocommerce_currency();

Do calculations in integer minor units (cents) when you can. See Taxes, Currency and Formatting.

Notices

PHP
wc_add_notice( __( 'Out of stock.', 'acme' ), 'error' );     // or 'success', 'notice'
wc_print_notices();

REST and Store API

Item Value
Admin REST namespace /wp-json/wc/v3/... (keys or auth)
Storefront API /wp-json/wc/store/v1/... (nonce or Cart-Token)
Own route register_rest_route() with a real permission_callback
Pagination headers X-WP-Total, X-WP-TotalPages
Webhook signature header X-WC-Webhook-Signature (base64 HMAC-SHA256 of the raw body)

See The REST API and the Store API.

Action Scheduler

PHP
as_enqueue_async_action( 'acme_sync_order', [ 'order_id' => $id ], 'acme' );
as_schedule_single_action( time() + HOUR_IN_SECONDS, 'acme_send_reminder', [ 'order_id' => $id ], 'acme' );
as_schedule_recurring_action( time(), DAY_IN_SECONDS, 'acme_daily_report', [], 'acme' );
as_unschedule_all_actions( 'acme_daily_report' );

WP-CLI

Terminal
wp wc product list --user=admin --fields=id,name,price
wp wc shop_order list --user=admin --status=processing
wp wc tool run regenerate_product_lookup_tables --user=admin
wp action-scheduler run
wp cron event list
wp option get woocommerce_db_version
wp wc hpos status

Subcommand names depend on the installed version; run wp wc --help to see yours. Use --user so REST-backed commands are authorized. Setup is covered in Development Environment and Tooling.

Debugging

PHP
// wp-config.php (development only)
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );

// WooCommerce logger
$logger = wc_get_logger();
$logger->info( 'Gateway called', [ 'source' => 'acme-gateway' ] );
$logger->error( 'Refund failed', [ 'source' => 'acme-gateway' ] );

Logs appear under WooCommerce, Status, Logs. Use Query Monitor for slow queries and hook callbacks. Never log secrets, card data or full personal data.

Security checklist

PHP
if ( ! current_user_can( 'manage_woocommerce' ) ) { wp_die( 'No access' ); }
check_admin_referer( 'acme_save' );
$text  = sanitize_text_field( wp_unslash( $_POST['text'] ?? '' ) );
$clean = wc_clean( wp_unslash( $_POST['field'] ?? '' ) );
echo esc_html( $text );
$wpdb->prepare( 'SELECT * FROM t WHERE id = %d', $id );

See Security for WooCommerce Extensions.

Common pitfalls

  • Forgetting to return from a filter.
  • Calling WC()->cart before it exists (admin, REST, early hooks).
  • Reading order data with get_post_meta() or WP_Query, which breaks under HPOS.
  • Stacking discounts because the price is recalculated from an already changed price.
  • Using floats for money and rounding in different places.
  • Caching cart, checkout or account pages, or putting nonces in cached HTML.
  • Treating a browser redirect as proof of payment; confirm with the provider.
  • Running work that takes minutes inside a request instead of Action Scheduler.
  • Copying a whole template when a hook would do, then ignoring outdated-template notices.
  • Not guarding for WooCommerce missing: wrap bootstrap code in a class_exists( 'WooCommerce' ) check (Your First WooCommerce Extension).

Two runnable stand-ins

PHP A status transition table

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.

PHP Round per line or per order?

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call writes a changed product price to storage?

    Setters only change the object in memory. save() persists the changes through the data store.
  2. 2. How do you read a custom order field in a way that works under HPOS?

    The order object reads from whichever storage is active.
  3. 3. What is the best place to declare HPOS compatibility?

    WooCommerce collects declarations on before_woocommerce_init, before it decides about features.
  4. 4. Which header carries the WooCommerce webhook signature?

    It holds a base64 HMAC-SHA256 of the raw body, signed with the webhook secret.

Summary

  • Get objects with wc_get_product() and wc_get_order(), change them with setters, and call save().
  • Use hooks for behavior, templates for markup, and the order API for HPOS-safe data access.
  • Use Action Scheduler for background work and wc_get_logger() for logs.
  • Validate, sanitize, escape, and check capabilities on every entry point.
  • Money belongs in integer minor units with one documented rounding rule.

You have reached the end of the track. Revisit Exercises With Solutions to practice, or start again from How WooCommerce Is Built.