Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Products and the CRUD Layer

Working With Products in Code

Create, read, update and query WooCommerce products from PHP with wc_get_product, WC_Product_Simple and wc_get_products, including stock, prices and visibility.

Almost every WooCommerce extension touches products: importing a catalog, adjusting prices, showing related items, syncing stock with a warehouse. All of that goes through the same handful of functions and classes. Once you know them, a task like "mark every item in a category as out of stock" is ten lines of code, and you can write it without a single SQL query.

This lesson builds on the CRUD basics from CRUD Classes and Data Stores. You will load products, create and update simple products, handle prices, stock and visibility, and query products with wc_get_products(). The WooCommerce calls are shown in read-only blocks; the runnable stand-in is a small product repository with the same query style so you can practise the arguments.

Loading a product

wc_get_product() takes an ID (or a post object) and returns the right class for the product type, or false if nothing matches:

PHP
$product = wc_get_product( 123 );

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

echo $product->get_name();
echo $product->get_type();      // 'simple', 'variable', 'grouped', 'external'
echo $product->get_price();     // the active price, a string

Always check for false before calling methods. The returned object is a subclass of WC_Product: WC_Product_Simple, WC_Product_Variable, WC_Product_Grouped or WC_Product_External, plus any custom type you register (see Custom Product Types). Code that must work for every type should depend on the shared WC_Product methods, such as is_purchasable(), is_in_stock() and get_price(), instead of testing the class.

WooCommerce represents money as strings such as "89.00". Do math on integers (cents) or with a decimal-safe approach, never with floats. See Money as Integers.

Creating a simple product

A new product is an object without an ID. Set properties, then save once:

PHP
$product = new WC_Product_Simple();

$product->set_name( 'Trail Backpack' );
$product->set_status( 'publish' );           // or 'draft', 'private'
$product->set_regular_price( '89.00' );
$product->set_sku( 'BP-TRAIL-01' );
$product->set_description( 'A 30 litre pack for day hikes.' );
$product->set_short_description( 'A 30 litre day pack.' );
$product->set_category_ids( array( 17, 21 ) );

$product_id = $product->save();               // returns the new ID

set_sku() throws a WC_Data_Exception if the SKU is already used by another product, because SKUs must be unique. Wrap import code in try/catch so one duplicate does not stop the whole batch:

PHP
try {
    $product->set_sku( $row['sku'] );
    $product->save();
} catch ( WC_Data_Exception $e ) {
    wc_get_logger()->warning( $e->getMessage(), array( 'source' => 'acme-import' ) );
}

Prices and sales

A product has a regular price, an optional sale price and optional sale dates. You set those; WooCommerce works out the active price (the _price value that carts and queries use) when the product is saved:

PHP
$product->set_regular_price( '89.00' );
$product->set_sale_price( '69.00' );
$product->set_date_on_sale_from( '2026-11-25' );
$product->set_date_on_sale_to( '2026-11-30' );
$product->save();

$product->get_price();         // active price right now
$product->is_on_sale();        // true while the sale applies

Do not set the active price directly to fake a discount; use the regular and sale fields so reports, sale badges and "was/now" displays all stay consistent. For discounts that depend on the customer or cart, change the price at cart time instead (see Dynamic Pricing, Fees and Discounts).

Stock

Stock has two layers: whether WooCommerce manages quantities for the product, and the status that shoppers see.

PHP
$product->set_manage_stock( true );
$product->set_stock_quantity( 25 );
$product->set_backorders( 'no' );             // 'no', 'notify', 'yes'
$product->save();

// Safer for concurrent changes than reading, adding and saving:
wc_update_product_stock( $product, 3, 'decrease' );

When stock is managed, WooCommerce derives the status (instock, outofstock, onbackorder) from the quantity. When it is not managed, you control the status yourself with set_stock_status(). For changes caused by many orders at once, prefer wc_update_product_stock() with 'increase' or 'decrease': it adjusts the stored number in one step instead of saving a quantity you read a moment ago. The ideas behind reservations and overselling are in Inventory Basics.

Visibility and catalog flags

Three separate things decide whether a customer sees a product:

  • Status: publish, draft, private, pending. Anything but publish is hidden from the public.
  • Catalog visibility: visible (shop and search), catalog (shop pages only), search (search only), hidden (nowhere, but the direct URL still works).
  • Featured: a flag that featured-product blocks and queries can use.
PHP
$product->set_catalog_visibility( 'search' );
$product->set_featured( true );
$product->save();

A common mistake is hiding a product by setting its stock to zero. That marks it "out of stock" (which may be exactly what you want); to remove it from listings, change visibility or status instead.

Querying with wc_get_products()

wc_get_products() returns product objects (or IDs) that match an array of arguments. It is the supported way to run product queries, and it understands WooCommerce concepts such as SKU, stock status and type, which a raw WP_Query does not.

PHP
$products = wc_get_products( array(
    'status'       => 'publish',
    'type'         => 'simple',
    'category'     => array( 'backpacks' ),   // category slugs
    'stock_status' => 'instock',
    'orderby'      => 'date',
    'order'        => 'DESC',
    'limit'        => 20,
    'page'         => 1,
) );

foreach ( $products as $product ) {
    echo $product->get_name(), ' ', $product->get_price(), "\n";
}

Useful arguments include limit (use -1 for everything, carefully), page, orderby, order, status, type, sku, category, tag, stock_status, featured, include and exclude. Two options change the shape of the result:

  • 'return' => 'ids' returns an array of IDs, which is much cheaper when you only need identifiers.
  • 'paginate' => true returns an object with products, total and max_num_pages, which is what a paged listing needs.

Loading thousands of full product objects exhausts memory. In bulk jobs, fetch IDs ('return' => 'ids') in pages of a few hundred, load and save each product, and let the loop end. For truly large work, hand pages to a queue (see Background Processing With Action Scheduler).

flowchart LR
    A["wc_get_products( args )"] --> B["WC_Product_Query"]
    B --> C["Product data store<br/>builds the query"]
    C --> D{"return = ids?"}
    D -->|"yes"| E["array of IDs"]
    D -->|"no"| F["array of WC_Product objects"]
    B --> G{"paginate = true?"}
    G -->|"yes"| H["object: products, total, max_num_pages"]

Arguments become a query on the data store; return and paginate decide the result shape.

A runnable stand-in

WooCommerce itself is not available on this site, so the stand-in below is a small repository over an array of products. It accepts the same style of arguments (status, category, stock_status, orderby, limit, page, return, paginate) and rejects duplicate SKUs the way set_sku() does. It is not WooCommerce code, but it lets you practise how the arguments combine.

PHP A product repository with wc_get_products-style arguments

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.

Notice that prices are integers (cents) in the stand-in and only formatted when printed. In real WooCommerce, prices are strings, so format and compare them with the price helper functions covered in Taxes, Currency and Formatting.

Updating many products safely

A typical update loop looks like this. Fetch IDs, load each product, change only what you need, save:

PHP
$ids = wc_get_products( array(
    'category' => array( 'clearance' ),
    'limit'    => 200,
    'return'   => 'ids',
) );

foreach ( $ids as $id ) {
    $product = wc_get_product( $id );
    if ( ! $product ) {
        continue;
    }
    $product->set_catalog_visibility( 'hidden' );
    $product->save();
}

Saving through the object keeps lookup tables, caches and the REST API in sync. Do not run UPDATE wp_postmeta ... for this; it skips every one of those steps.

A second runnable example is not needed here because the stand-in already covers the query shapes. The next stand-in, in Variations, Attributes and Taxonomies, takes on a harder case: products built from combinations.

PHP Why set_sku can throw: a tiny import loop

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 ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does wc_get_product() return when the ID does not belong to a product?

    The function returns false, so you must check the result before calling methods on it.
  2. 2. Which is the right way to give a product a temporary discount?

    Regular price, sale price and sale dates feed the active price, sale badges and reports consistently. Faking the active price breaks that.
  3. 3. Which argument makes wc_get_products() return only IDs?

    'return' => 'ids' skips building full product objects, which saves memory in bulk jobs.
  4. 4. A product has catalog visibility set to hidden. What is true?

    Catalog visibility only controls listings and search. Status and stock are separate settings.
  5. 5. Why does set_sku() sometimes throw in an import?

    WooCommerce enforces unique SKUs and throws WC_Data_Exception, so imports should catch it per row.

Summary

  • wc_get_product() returns a WC_Product subclass or false; check before use.
  • Create products with new WC_Product_Simple(), call setters, then save() once.
  • Set regular price, sale price and dates; WooCommerce derives the active price.
  • Manage stock with set_manage_stock() and wc_update_product_stock(); control visibility with status and catalog visibility, not stock.
  • wc_get_products() queries by SKU, category, stock status and more; use 'return' => 'ids' and paging for big jobs.

Next: Variations, Attributes and Taxonomies