12 KiB
Register Product Collection
The __experimentalRegisterProductCollection
function is part of the @woocommerce/blocks-registry
package. This function allows 3PDs to register a new collection. This function accepts most of the arguments that are accepted by Block Variation.
[!WARNING] It's experimental and may change in the future. Please use it with caution.
There are two ways to use this function:
-
Using
@woocommerce/dependency-extraction-webpack-plugin
in a Webpack configuration: This will allow you to import the function from the package & use it in your code. For example:import { __experimentalRegisterProductCollection } from "@woocommerce/blocks-registry";
-
Using the global
wc
object: This will allow you to use the function using the global JS object without importing it. For example:wc.wcBlocksRegistry.__experimentalRegisterProductCollection({ ... });
[!TIP] The first method is recommended if you are using Webpack.
Defining a Collection
We will explain important arguments that can be passed to __experimentalRegisterProductCollection
. For other arguments, you can refer to the Block Variation documentation.
A Collection is defined by an object that can contain the following fields:
name
(typestring
): A unique and machine-readable collection name. We recommend using the format<plugin-name>/product-collection/<collection-name>
. Both<plugin-name>
and<collection-name>
should consist only of alphanumeric characters and hyphens (e.g.,my-plugin/product-collection/my-collection
).title
(typestring
): The title of the collection, which will be displayed in various places including the block inserter and collection chooser.description
(optional, typestring
): A human-readable description of the collection.innerBlocks
(optional, typeArray[]
): An array of inner blocks that will be added to the collection. If not provided, the default inner blocks will be used.isDefault
: ⚠️ It's set tofalse
for all collections. 3PDs doesn't need to pass this argument.isActive
: ⚠️ It will be managed by us. 3PDs doesn't need to pass this argument.
Attributes
Attributes are the properties that define the behavior of the collection. All the attributes are optional. Here are some of the important attributes that can be passed to __experimentalRegisterProductCollection
:
-
query
(typeobject
): The query object that defines the query for the collection. It can contain the following fields:offset
(typenumber
): The number of items to offset the query by.order
(typestring
): The order of the query. Accepted values areasc
anddesc
.orderBy
(typestring
): The field to order the query by.pages
(typenumber
): The number of pages to query.perPage
(typenumber
): The number of products per page.search
(typestring
): The search term to query by.taxQuery
(typeobject
): The tax query to filter the query by. For example, if you wanna fetch products with categoryClothing
&Accessories
and tagSummer
then you can passtaxQuery
as{"product_cat":[20,17],"product_tag":[36]}
. Where array values are the term IDs.featured
(typeboolean
): Whether to query for featured items.timeFrame
(typeobject
): The time frame to query by.operator
(typestring
): The operator to use for the time frame query. Accepted values arein
andnot-in
.value
(typestring
): The value to query by. It should be a valid date string that PHP'sstrtotime
function can parse.
woocommerceOnSale
(typeboolean
): Whether to query for items on sale.woocommerceStockStatus
(typearray
): The stock status to query by. Some of the accepted values areinstock
,outofstock
,onbackorder
.woocommerceAttributes
(typearray
): The attributes to query by.- For example, if you wanna fetch products with color
blue
&gray
and sizeLarge
then you can passwoocommerceAttributes
as[{"termId":23,"taxonomy":"pa_color"},{"termId":26,"taxonomy":"pa_size"},{"termId":29,"taxonomy":"pa_color"}]
.
- For example, if you wanna fetch products with color
woocommerceHandPickedProducts
(typearray
): The hand-picked products to query by. It should contain the product IDs.priceRange
(typeobject
): The price range to query by.min
(typenumber
): The minimum price.max
(typenumber
): The maximum price.
-
displayLayout
(typeobject
): The display layout object that defines the layout of the collection. It can contain the following fields:type
(typestring
): The type of layout. Accepted values aregrid
andstack
.columns
(typenumber
): The number of columns to display.shrinkColumns
(typeboolean
): Whether the layout should be responsive.
-
hideControls
(typearray
): The controls to hide. Possible values:order
- "Order by" settingattributes
- "Product Attributes" filtercreated
- "Created" filterfeatured
- "Featured" filterhand-picked
- "Hand-picked Products" filterkeyword
- "Keyword" filteron-sale
- "On Sale" filterstock-status
- "Stock Status" filtertaxonomy
- "Product Categories", "Product Tags" and custom taxonomies filtersprice-range
- "Price Range" filter
Preview Attribute
The preview
attribute is optional, and it is used to set the preview state of the collection. It can contain the following fields:
initialPreviewState
(typeobject
): The initial preview state of the collection. It can contain the following fields:isPreview
(typeboolean
): Whether the collection is in preview mode.previewMessage
(typestring
): The message to be displayed in the Tooltip when the user hovers over the preview label.
setPreviewState
(optional, typefunction
): The function to set the preview state of the collection. It receives the following arguments:setState
(typefunction
): The function to set the preview state. You can pass a new preview state to this function containingisPreview
andpreviewMessage
.attributes
(typeobject
): The current attributes of the collection.location
(typeobject
): The location of the collection. Accepted values areproduct
,archive
,cart
,order
,site
.
For more info, you may check PR #46369, in which the Preview feature was added
Examples
Example 1: Registering a new collection
__experimentalRegisterProductCollection({
name: "your-plugin-name/product-collection/my-custom-collection",
title: "My Custom Collection",
icon: "games",
description: "This is a custom collection.",
keywords: ["custom collection", "product collection"],
});
As you can see in the example above, we are registering a new collection with the name woocommerce/product-collection/my-custom-collection
& title My Custom Collection
. Here is screenshot of how it will look like:
Example 2: Register a new collection with a preview
As you can see below, setting the initial preview state is possible. In the example below, we are setting isPreview
and previewMessage
.
__experimentalRegisterProductCollection({
name: "your-plugin-name/product-collection/my-custom-collection-with-preview",
title: "My Custom Collection with Preview",
icon: "games",
description: "This is a custom collection with preview.",
keywords: ["My Custom Collection with Preview", "product collection"],
preview: {
initialPreviewState: {
isPreview: true,
previewMessage:
"This is a preview message for my custom collection with preview.",
},
},
attributes: {
query: {
perPage: 5,
featured: true,
},
displayLayout: {
type: "grid",
columns: 3,
shrinkColumns: true,
},
hideControls: [ "created", "stock-status" ]
},
});
Here is how it will look like:
Example 3: Advanced usage of preview
As you can see below, it's also possible to use setPreviewState
to set the preview state. In the example below, we are setting initialPreviewState
and using setPreviewState
to change the preview state after 5 seconds.
This example shows:
- How to access current attributes and location in the preview state
- How to use async operations
- We are using
setTimeout
to change the preview state after 5 seconds. You can use any async operation, like fetching data from an API, to decide the preview state. - How to use the cleanup function as a return value
- We are returning a cleanup function that will clear the timeout after the component is unmounted. You can use this to clean up any resources you have used in
setPreviewState
.
__experimentalRegisterProductCollection({
name: "your-plugin-name/product-collection/my-custom-collection-with-advanced-preview",
title: "My Custom Collection with Advanced Preview",
icon: "games",
description: "This is a custom collection with advanced preview.",
keywords: [
"My Custom Collection with Advanced Preview",
"product collection",
],
preview: {
setPreviewState: ({
setState,
attributes: currentAttributes,
location,
}) => {
// setPreviewState has access to the current attributes and location.
// console.log( currentAttributes, location );
const timeoutID = setTimeout(() => {
setState({
isPreview: false,
previewMessage: "",
});
}, 5000);
return () => clearTimeout(timeoutID);
},
initialPreviewState: {
isPreview: true,
previewMessage:
"This is a preview message for my custom collection with advanced preview.",
},
},
});
Example 4: Collection with inner blocks
As you can see below, it's also possible to define inner blocks for the collection. In the example below, we are defining inner blocks for the collection.
__experimentalRegisterProductCollection({
name: "your-plugin-name/product-collection/my-custom-collection-with-inner-blocks",
title: "My Custom Collection with Inner Blocks",
icon: "games",
description: "This is a custom collection with inner blocks.",
keywords: ["My Custom Collection with Inner Blocks", "product collection"],
innerBlocks: [
[
"core/heading",
{
textAlign: "center",
level: 2,
content: "Title of the collection",
},
],
[
"woocommerce/product-template",
{},
[
["woocommerce/product-image"],
[
"woocommerce/product-price",
{
textAlign: "center",
fontSize: "small",
},
],
],
],
],
});
This will create a collection with a heading, product image, and product price. Here is how it will look like:
![TIP] You can learn more about inner blocks template in the Inner Blocks documentation.
![TIP] You can also take a look at how we are defining our core collections at
plugins/woocommerce-blocks/assets/js/blocks/product-collection/collections
directory. Our core collections will also evolve over time.