I want to change the Category that a Store Grid Product Gallery uses dynamically. Is there a way to do this? In image below, you’ll see that the category can be selected manually in editor. I want to change this dynamically when the page loads via JavaScript $w. based some other data I have…
Figured out a way to do this, thought it might not be officially supported.
Based on wix-stores-v2/collections, you can use wix-data to query your catalogs. I did this with backend code but I believe it would work with frontend code as well (wix-data can be used in the frontend).
export const queryCollectionByName = webMethod(
Permissions.Anyone,
async (categoryName) => {
const { items } = await wixData.query("Stores/Collections").eq('name', categoryName).find();
if (items.length === 1) {
return items[0];
}
return undefined;
}
);
Basically if I have a specific category I want to use, I will call that function to get the collection information which looks like:
{
_id: "some hex string",
name: "Category Name",
mainMedia: "wix:image://...",
slug: "same as name but lowercase and no spaces",
categoryPageUrl: "/category/slug",
}
If you have the _id
from above, you can change the category of your Product Grid Gallery. The setCollection
function is not documented in the Velo ($w) API but I discovered it by logging $w('#gridGallery1')
to console. Hence I’m not sure if this will always work.
async function initialize() {
// for me, productCategory comes from my `#dynamicDataset`
await $w('#dynamicDataset').onReadyAsync();
const { productCategory } = $w('#dynamicDataset').getCurrentItem();
const storeCategory = await queryCollectionByName(productCategory);
if (storeCategory) {
await $w('#gridGallery1').setCollection(storeCategory._id);
}
}
$w.onReady(initialize);