Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon how can I use the wc_get_products method to fetch all products at once


how can I use the wc_get_products method to fetch all products at once


The `wc_get_products` method in WooCommerce is a powerful function used to fetch multiple products programmatically based on specified criteria. To fetch all products at once, you primarily use the `limit` parameter and adjust other parameters based on your filtering needs. Here is a comprehensive overview of how to use `wc_get_products` to get all products and manage product queries effectively.

Basic Usage to Fetch All Products

To fetch all products without any limitation, you set the `limit` parameter to `-1`. This instructs WooCommerce to ignore pagination limits and return every product available that matches the other query criteria. For example:

php
$products = wc_get_products(array('limit' => -1));

This returns an array containing objects of the type `WC_Product` representing all products stored in WooCommerce.

Parameters of wc_get_products

`wc_get_products` takes one argument: an associative array (`$args`) that defines the query parameters. These parameters let you filter and customize which products are returned. Important parameters include:

- `limit`: Integer. The number of products to return. Use `-1` to retrieve all products.
- `status`: Specifies the post status of products, for example `publish` for live products.
- `type`: Filters the product type, such as `simple`, `variable`, `grouped`, etc.
- `category`: Array of category slugs, to get products from specific categories.
- `product_category_id`: Array or integer of category IDs.
- `include`: Array of product IDs to specifically include in the query.
- `exclude`: Array of product IDs to exclude from the results.
- `orderby`: Field to order results by, like `ID`, `date`, `title`.
- `order`: Sort order, `ASC` or `DESC`.
- `paginate`: Boolean, if true returns paginated results with pagination metadata.
- `return`: Defines the return type, commonly `objects` (WC_Product objects).

You combine these parameters to tailor the product query as needed.

Example: Fetch All Published Products

You often want only published products (those visible in the store). To do this, add the `status` parameter:

php
$args = array(
  'limit' => -1,
  'status' => 'publish',
);
$products = wc_get_products($args);

Then you can iterate over `$products` to access product details:

php
foreach ($products as $product) {
  echo $product->get_name() . '';
}

Types of Products

WooCommerce products can be of various types like `simple`, `variable`, `grouped`, `external`, etc. Use the `type` parameter to fetch only specific types:

php
$args = array(
  'limit' => -1,
  'type' => 'variable',
);
$variable_products = wc_get_products($args);

This fetches all variable products only.

Filtering by Category

You can fetch products that belong to particular categories in two ways: by category slug or by category ID.

By slug:

php
$args = array(
  'limit' => -1,
  'category' => array('clothing', 'shoes'),
);
$products = wc_get_products($args);

By category ID:

php
$args = array(
  'limit' => -1,
  'product_category_id' => array(12, 34),
);
$products = wc_get_products($args);

Including and Excluding Specific Products

You can customize results by including only specific product IDs or excluding others using:

php
$args_include = array(
  'include' => array(10, 20, 30),
);
$include_products = wc_get_products($args_include);

$args_exclude = array(
  'limit' => -1,
  'exclude' => array(15, 25, 35),
);
$exclude_products = wc_get_products($args_exclude);

Pagination and Offset

If you want to control how many products are retrieved per page or skip some products, you can use `limit`, `page`, and `offset`:

- `limit`: Number of products per page or batch.
- `page`: The page number to retrieve.
- `offset`: Number of products to skip.

This can be useful when dealing with thousands of products to avoid memory overload:

php
$args = array(
  'limit' => 100,
  'page' => 1,
);
$products_page1 = wc_get_products($args);

Accessing Product Data

Each item returned by `wc_get_products` is a `WC_Product` object. This class provides methods to get product details:

- `get_id()`: Get product ID.
- `get_name()`: Get the product name.
- `get_price()`: Get price.
- `get_type()`: Product type.
- `get_sku()`: SKU.
- `get_description()`: Full description.
- `get_short_description()`: Short description.
- `get_stock_quantity()`: Stock count.
- `is_in_stock()`: Stock status.
- `get_image()`: Product image URL.

Example to display product details:

php
foreach($products as $product) {
  echo 'ID: ' . $product->get_id() . '';
  echo 'Name: ' . $product->get_name() . '';
  echo 'Price: ' . $product->get_price() . '';
}

Handling Large Numbers of Products Efficiently

Fetching thousands of products at once (e.g., 2000 or more) can lead to memory or performance issues. Techniques to manage this include:

- Using pagination with `limit` and `page` parameters to load products in batches.
- Using `offset` to skip already processed products in loops.
- Processing products incrementally when performing actions like exporting or modifying bulk data.

Example loop fetching products 100 at a time:

php
$page = 1;
do {
  $args = array(
    'limit' => 100,
    'page' => $page,
  );
  $products = wc_get_products($args);

  foreach ($products as $product) {
    // Process each product
  }

  $page++;
} while (count($products) > 0);

This avoids loading all products simultaneously.

Common Use Cases

- Display all products or filtered lists on a front-end page.
- Export product data for reporting or integration.
- Bulk update product meta or pricing programmatically.
- Build custom product search and filter features.
- Retrieve products for API endpoints in custom plugins.

Summary

The `wc_get_products` function is the key method in WooCommerce to programmatically retrieve any set of products. To fetch all products, the critical step is setting `'limit' => -1`. Beyond that, combining other parameters allows granular queries by status, type, category, IDs, and more. Handling large volumes efficiently involves pagination to prevent performance degradation.

Using the returned `WC_Product` objects, developers can access virtually all product-related data through available methods, facilitating robust e-commerce customizations tailored to specific needs.

This method is preferred over `wc_get_product`, which is designed to retrieve single product objects. `wc_get_products` is truly built for multiple product queries and is flexible to meet complex querying requirements in WooCommerce stores of any size.

References for detailed usage and parameter explanations are available in WooCommerce official documentation and community resources.