Trying to see if a Product is assigned to a particular Catagory

I’m having trouble with finding out if a Product has a particular Catagory.

On my Product Page I have this Code.

import wixData from ‘wix-data’;
$w.onReady(function () {
$w(“#productPage1”).getProduct()
.then((product) => {
let ProdNam = product.name
console.log("Product name is: ", ProdNam);
});
});

Which works..
Now what I need to do is to check this this Product has a Catagory of “HasPerCat”. I don’t need to retrieve any of the catalogues, but I do need to verify True/False.

I have tried atleast 4 different ways using examples from the the web.. But I just cannot get one to work,

Can anyone help me.
Many many thanks in advance.

Dave

Yes, you can do this, but you need to check the product against the Wix Stores collection data, not just the product object returned by getProduct().

In Wix Stores, categories/collections are stored against the product in the Stores/Products collection under the collections field. That field is a multiple-reference field and can be filtered using hasSome. Wix also notes that the collection ID appears in the hidden collections.id field, which is what you can use to check whether the product belongs to a specific collection/category.

Many many thanks for the tip.

Could you point me to an example. I find it best if I use existing code and prod/change it till I get it to work.

This will be running on the Front End, although in time I will take these types of data lookup functions to the Backend to speed up Browser time. In the 90’s I did a lot of work with ASP with Ajax.

Again thanks for your quick reply - I am working hard on getting my website running.
Sincerely
Dave

You might be best to use the Wix SDK, which has a method for listCategoriesForItem, so given the product ID, it will return a list of categories that contain the specified item - List Categories For Item | API Reference

2 things to note:

  • This works for Catalog V3. You can check if you’re store is Catalog V1 or V3 using this SDK - Get Catalog Version | API Reference
  • These specific SDKs will need to be called from backend code, so you’ll need to work with backend code from the get go when working with them