Dynamic Product Pages / CMS / Personalised Product Pages

Continuing the discussion from Displaying Collection Content on Wix Stores Product Page:

You will have to write a few lines of code to collapse the section if there is no description associated with that product in the CMS, or expand it if there IS a description available.

Here’s an example when using datasets:

import wixData from "wix-data";
import wixLocationFrontend from "wix-location-frontend";

let product;

$w.onReady(function () {
  initDataset();
});

wixLocationFrontend.onChange((location) => {
  let newPath = location.path;
  if (newPath?.[0] === "product-page") {
    initDataset();
  }
});

async function initDataset() {
   $w("#myDataset").onReady(() => {
    let itemObj = $w("#myDataset").getCurrentItem();
    if (itemObj) {
      $w("#descriptionSection").expand();
   } else {
      $w("#descriptionSection").collapse();
   }
  });
}

Here’s another example using wix-data:

import wixData from "wix-data";
import wixLocationFrontend from "wix-location-frontend";

let product;

$w.onReady(function () {
  initProductPage();
});

wixLocationFrontend.onChange((location) => {
  let newPath = location.path;
  if (newPath?.[0] === "product-page") {
    initProductPage();
  }
});

async function initProductPage() {
  product = await $w("#productPage1").getProduct();
  wixData
  .query("myCollection")
  .eq("reference", product._id)
  .find()
  .then((results) => {
    if (results.items.length > 0) {
     $w("#descriptionSection").expand();
    } else {
     $w("#descriptionSection").collapse();
    }
  })
  .catch((err) => {
    console.log(err);
  });
}

NOTE: Make sure to change the IDs of the datasets, collections, fields & sections for this code to work. Also ensure that your collection’s Read permissions are set to Everyone. More on that here.