How to get WooCommerce products using wc_get_products
In this article, we’ll dive into the practical uses of the wc_get_products()
function in WooCommerce. Specifically, we’ll focus on how to query and retrieve products using various parameters. By effectively understanding and leveraging these parameters, you can streamline your product management and enhance your WooCommerce store’s functionality. We’ll cover each parameter in detail, providing clear examples to demonstrate their application in real-world scenarios.
How to use the wc_get_products() function
The wc_get_products()
function is a versatile tool in WooCommerce for fetching products. It accepts a single parameter: an array of arguments, allowing you to specify the criteria for the products you want to retrieve. The function returns an array of WC_Product
objects, each representing a product that matches your criteria. The WC_Product
class in WooCommerce can be used to access various product data, providing an easy way to manage and update information about each product.
Here’s a simple example to illustrate its usage. In this code snippet, we retrieve all the products and loop through them to display their names:
$args = array('orderby' => 'ID', 'limit' => -1); $products = wc_get_products($args); foreach ( $products as $product ) { echo $product->get_name() . "<br>"; }
In this example, we’ve set the orderby
option in $args
to sort the products by ID. We also set the limit
option to -1, meaning that all products will be fetched. The foreach loop then iterates through each product object, using the get_name()
method of the WC_Product
class to display the name of each product.
Querying multiple products vs single product
wc_get_products()
is designed for querying multiple products in WooCommerce, making it ideal for retrieving lists or arrays of products. If you need to find a single product, wc_get_product()
is the more appropriate function, as it focuses on retrieving the data of an individual product based on its attributes.
The limit parameter
The limit parameter in the wc_get_products()
function is crucial for controlling the number of products retrieved by your query. It accepts an integer value, which represents the maximum number of product results to return. You can also set this parameter to -1 for an unlimited number of results. If you don’t specify a value for limit, it defaults to the value set in the global posts_per_page option in WordPress.
Retrieving All Products
To get all products without any limitation, set the limit
parameter to -1:
$products = wc_get_products(array('limit' => -1));
Retrieving a Specific Number of Products
If you want to retrieve a specific number of products, simply set the limit
parameter to your desired number. For example, to get the first 20 products, you can use the following code snippet:
$products = wc_get_products(array('limit' => 20));
Setting the sorting order of the products result
The orderby and order parameters in wc_get_products()
allow you to sort the products retrieved based on specific criteria:
orderby
– determines the criterion by which the products are sorted in the query results. It aaccepts strings like ‘none’, ‘ID’, ‘name’, ‘type’, ‘rand’, ‘date’, and ‘modified’. The default value is ‘date’, which means that products are sorted by the date created.- order – parameter works in conjunction with
orderby
and accepts either ‘DESC’ for descending order or ‘ASC’ for ascending order. The default value is ‘DESC’.
Here is an example usage:
$products = wc_get_products(array('orderby' => 'name', 'order' => 'ASC'));
This code retrieves products sorted alphabetically by their names, from A to Z. It sets the orderby
parameter to ‘name’ and the order
parameter to ‘ASC’.
Using the status parameter
The status
parameter in wc_get_products()
is crucial for filtering products based on their publication status. This parameter can accept either a single status string or an array of status strings. By default, if the status
parameter is not specified, it includes all WordPress default post statuses: ‘draft’, ‘pending’, ‘private’, and ‘publish’.
To query only the products that are currently published, you can set the status
parameter to ‘publish’:
$args = array('status' => 'publish'); $products = wc_get_products($args);
In this example, the function fetches products that have a status of ‘publish’. This parameter is particularly important for controlling the visibility of products in your queries. For instance, you might only want to display products that are available to the public (published) on your storefront while excluding those in draft or pending review.
Using the type parameter
The type
parameter is used to get products based on their product type. This parameter can take either a single string or an array of strings, specifying the types of products you wish to retrieve. The common types include ‘external’, ‘grouped’, ‘simple’, ‘variable’, and any custom types you may have added.
For example, to find all variable products, you can set the type parameter to ‘variable’:
$args = array('type' => 'variable'); $products = wc_get_products($args);
In this example, the function will return products classified as variable. Variable products in WooCommerce are those that have variations, like a shirt that comes in different sizes or colors.
Get WooCommerce products by ID
The include
and exclude
parameters in the wc_get_products()
function offer direct control over which products are retrieved based on their IDs. These parameters are especially useful for targeting or omitting specific products from your query results.
The include parameter
The include
parameter accepts an array of product IDs. The query results will include only products with IDs in this array.
$args = array('include' => array(10, 20, 30)); $products = wc_get_products($args);
This code snippet will fetch products that have the IDs 10, 20, and 30.
The exclude Parameter
The exclude
parameter, on the other hand, accepts an array of product IDs that will not be included in the query results.
$args = array('exclude' => array(15, 25, 35)); $products = wc_get_products($args);
In this example, products with the IDs 15, 25, and 35 will be omitted from the results.
Querying products by name
The name
parameter in wc_get_products()
allows you to query products based on their names. This is particularly useful when you want to retrieve a product or a set of products with a specific title.
$products = wc_get_products(array('name' => 'Sample Product'));
This code will search for and retrieve all products named “Sample Product”.
Get products by category
With the wc_get_products()
function, you can query products based on their category using two parameters: category
and product_category_id
. These parameters can be useful in various situations when you need the products segmented by category, such as when creating custom category pages.
Using the category Parameter
The category
parameter accepts an array of category slugs. It’s useful when you know the slugs of the categories you want to query.
To retrieve products from specific categories using their slugs, your code would look like this:
$args = array('category' => array('electronics', 'books')); $products = wc_get_products($args);
In this example, the function fetches products that are in either the ‘electronics’ or ‘books’ categories. The products must have at least one of the categories assigned in order to be returned in the results.
Using the product_category_id Parameter
The product_category_id
parameter accepts either a single ID or an array of IDs. It’s useful when you have the category IDs and want to query products based on these IDs.
To retrieve products from categories using their IDs, you can use the following code:
$args = array('product_category_id' => array(12, 34)); $products = wc_get_products($args);
Here, products from categories with IDs 12 or 34 will be retrieved.
WooCommerce product tag parameters
In WooCommerce, you can refine your product queries using the tag and product_tag_id
parameters to filter products based on their tags. This is useful for segmenting products with common characteristics or themes represented by tags.
The tag parameter
The tag
parameter accepts an array of tag slugs. It includes products that are assigned specific tags identified by their slugs.
To fetch products associated with the ‘best-seller’ or ‘new-arrival’ tags using their slugs, you can use the tag
parameter like this:
$args = array('tag' => array('best-seller', 'new-arrival')); $products = wc_get_products($args);
When using the tag parameter, the products retrieved need to match at least one of the specified tag slugs; it is not necessary for all the provided tag slugs to be met for a product to be included in the results.
The product_tag_id parameter
The product_tag_id
parameter, on the other hand, accepts either a single ID or an array of IDs. This parameter is used to filter products based on their tag IDs.
For example, to query products that are tagged with IDs 101 or 102, you can use the following code:
$args = array('product_tag_id' => array(101, 102)); $products = wc_get_products($args);
Similarly, at least one of the specified tag IDs needs to match in order for a product to be included in the results.
Get products by SKU
The sku
parameter in the wc_get_products()
function allows you to get products based on their SKU (Stock Keeping Unit). This parameter is particularly useful for locating specific products or a range of products that share similar SKU patterns. Notably, the SKU parameter supports partial matching, enabling you to find products whose SKUs contain a specified substring.
Querying Products with an Exact SKU Match
For a direct, exact match to a specific SKU, just set the full SKU to the sku
parameter:
$args = array('sku' => 'ABC123'); $products = wc_get_products($args);
This code will retrieve the products that have an exact SKU of ‘ABC123’.
Querying Products with a partial SKU Match
If you want to find products with SKUs that partially match a certain pattern, you can also do so. For instance:
$args = array('sku' => 'ABC'); $products = wc_get_products($args);
In this case, the function will return products with SKUs that include ‘ABC’ as a part of their SKU string (like ‘ABC123′, ’00ABC00’, etc.). This is beneficial when you’re looking to group or identify products that follow a certain SKU naming convention but may have variations in their complete SKU.
Querying WooCommerce products by price
In WooCommerce, you can query products based on their price using parameters like price
, regular_price
, and sale_price
. Each of these parameters targets a different aspect of a product’s pricing structure:
price
– targets the current active price of a product, which could be a regular price or a discounted sale priceregular_price
– searches based on the product’s regular price, disregarding any current sale pricessale_price
– targets products that are currently on sale, allowing you to query products based on their discounted price.
Let’s say you want to find products that are currently priced at $50. You would use the price parameter in your query like this:
$args = array('price' => 50.0); $products = wc_get_products($args);
This code will fetch products whose current selling price is exactly $50. This might include products normally priced higher but currently on sale for $50, as well as products whose regular price is $50.
Get WooCommerce products by number of sales
The total_sales
parameter in wc_get_products()
is used to query products based on the number of sales they have made.
For example, to find products that have not yet made any sales, you can set the total_sales
parameter to zero.
$args = array('total_sales' => 0); $products = wc_get_products($args);
Querying products by stock status
The stock_status
parameter allows you to filter products based on their stock availability. This parameter is particularly useful for managing product displays according to inventory status. It accepts either ‘outofstock’ or ‘instock’ as values.
Rrerieving In-Stock products
If you want to retrieve products that are currently in stock, set the stock_status
parameter to ‘instock’:
$args = array('stock_status' => 'instock'); $products = wc_get_products($args);
Rrerieving Out-of-Stock products
To find products that are currently out of stock, set the stock_status
parameter to ‘outofstock’:
$args = array('stock_status' => 'outofstock'); $products = wc_get_products($args);
Stock quantity
Additionally, you can use the stock_quantity
parameter to query products based on the quantity of stock available.
$args = array('stock_quantity' => 5); $products = wc_get_products($args);
This code will retrieve products that have a stock quantity of exactly 5 units. This type of query is particularly useful when you need to identify products with low stock for restocking purposes or to highlight items with limited availability on your store.
Get products by date
In WooCommerce, you can query products based on various date parameters:
date_created
– refers to the date when the product was createddate_modified
– indicates when the product was last modifieddate_on_sale_from
– specifies the starting date of a product’s sale perioddate_on_sale_to
: defines the end date of a product’s sale period.
These parameters accept dates in standard formats, allowing for precise and flexible querying:
YYYY-MM-DD
: Matches products on that specific day (site timezone).>
,<
,>=
,<=
+YYYY-MM-DD
: Matches products after, before, on or after, and on or before that day (site timezone). For example on or after would use the following format:>=YYYY-MM-DD
YYYY-MM-DD...YYYY-MM-DD
: Matches products during or between those days (site timezone).- Using
TIMESTAMP
instead ofYYYY-MM-DD
matches the exact second in UTC timezone, with the same variations as above.
Let’s see an example. Suppose you want to find products that were created after January 1, 2024. You would use the date_created
parameter as follows:
$args = array('date_created' => '>=2024-01-01'); $products = wc_get_products($args);
Paginating the list of products
When working with a large number of products, pagination becomes essential. WooCommerce’s wc_get_products()
function supports pagination through the page
, paginate
, and offset
parameters. These parameters help in breaking down the product list into manageable chunks or pages.
The page parameter
The page parameter specifies which page of results to retrieve. It’s used in conjunction with the limit parameter to define the number of products per page.
$args = array('limit' => 5, 'page' => 2); $products = wc_get_products($args);
In this example, you’ll get the second set of 5 products.
The offset parameter
The offset parameter is used to skip a certain number of products before starting to return the results. It’s particularly useful when you need to start displaying products from a certain position.
For example, to skip the first 10 products and then retrieve the next 5, you can use the following code snippet:
$args = array('limit' => 5, 'offset' => 10); $offset_products = wc_get_products($args);
The paginate parameter
Setting the paginate
parameter to true
modifies the return type of the query. Instead of returning just an array of products, it returns an object with the fields:
products
– the array of found productstotal
– total number of found productsmax_num_pages
– total number of pages
This is useful when you want to display a pagination including the total number of products and number of pages.
Let’s see an example:
$args = array('limit' => 5, 'page' => 2, 'paginate' => true); $result = wc_get_products($args); // Display total number of pages and total number of products echo "Total pages: " . $result->max_num_pages . "<br>"; echo "Total products: " . $result->total . "<br>"; // Loop through each product and display its name foreach ($result->products as $product) { echo $product->get_name() . "<br>"; }
The return parameter
The return
parameter in wc_get_products()
controls the data format the function returns. It’s a flexible feature that allows you to specify the type of information you receive about the queried products. This parameter accepts two values: ‘ids’ or ‘objects’.
When set to ‘ids’, the function returns an array of product IDs. This is useful when you need a simple list of IDs for further processing or when you need to reference products without requiring full details.
The default value for return
is ‘objects’. In this mode, the function returns an array of product objects. Each object in this array is an instance of the WC_Product
class, containing all the properties and methods applicable to the individual products. This is useful when you need detailed information about each product, including methods to manipulate or display product data.
If you want to get only the IDs of the products, your query would look like this:
$args = array('return' => 'ids'); $product_ids = wc_get_products($args); // returns product IDs like [1, 2, 3]
wc_get_products() vs WC_Product_Query
The wc_get_products()
function and the WC_Product_Query
class in WooCommerce serve similar purposes but differ in their approach. While wc_get_products()
is a more straightforward function that, WC_Product_Query
offers a more object-oriented approach. Both accept the same parameters, allowing for similar levels of flexibility and control over product queries. In fact, wc_get_products()
uses WC_Product_Query
behind the scenes.
Here is a basic example of using the WC_Product_Query
class:
$args = array('limit' => 10, 'orderby' => 'date', 'order' => 'DESC'); $query = new WC_Product_Query($args); $products = $query->get_products(); foreach ($products as $product) { echo $product->get_name() . "<br>"; }
Accessing product sales data
If you’re looking to get more detailed data and reports from your WooCommerce store, you might consider using the Users Insights plugin, which uses the rich product information from WooCommerce to create advanced product reports. These reports cover best-selling products, how well each product is selling, which products are frequently bought together, and how different product variations and attributes perform. This tool makes it easier to understand what your customers are buying and why, helping you make better decisions about what to stock and sell. To learn more, head over to the WooCommerce Product Reports page.
Conclusion
The wc_get_products()
function in WooCommerce is essential for any developer looking to efficiently manage and manipulate product data. By understanding and utilizing its various parameters – from sorting and filtering by categories, tags, and SKUs, to advanced queries based on price, stock status, and sales data – you can greatly enhance the functionality and user experience of WooCommerce stores.