Create calculated ratings reviews for Wix Stores Product page
About
Our Wix Stores Products page reviews tutorial was released in February. It was made up of 10 very short and concise video tutorial that explained how to add reviews in 5 steps. The short videos are between 30 seconds to 4 minutes long. This tutorial is a continuation of the first tutorial as it allowed us to create the important foundational code for our ratings and reviews function.
If you have not completed that tutorial yet, please do so before beginning this one. Here is a link to the first tutorial:
https://www.totallycodable.com/post/create-filtered-product-reviews-for-wix-stores-product-page
Even if you are an experienced coder it is best you start with that first tutorial because we do not code and configure our elements and databases like Wix does in their tutorials. (We think more simplistically, making our approach in teaching our tutorials unique.) If you followed Wix's tutorial to add ratings and reviews, this is not a tutorial with the same code or structure. It is a different method and approach.
At the end of this tutorial you will learn how to:
- Enhance the existing review function created by Code Queen
- Create a database to store pre-calculated ratings from reviews previously submitted
- Create a calculated rating to display on Wix Stores product page
- Append code to existing review function code
Link to live tutorial site with fully functioning code: https://codequeen.wixsite.com/wix-stores-ratings/product-page/the-eyes
Follow Along #1
Content Manager: Create and configure database
For our tutorial, we will be collecting reviews from a public visitor on the website. Since we want our ratings database updated automatically we want to make sure we have the correct field and permission set up. The video below has no audio. The video covers the first steps you need to take:
- Make sure DevMode is turned on
- Expand and Collapse the side panel as needed to access Content Collection databases
- Create a new collection called Ratings
- Set additional settings to Custom Use
- Set custom permissions for read Anyone, create Anyone, update Anyone and delete Admin
- Begin by adding the appropriate database fields to save the data we will be collecting
- Add a text field called Product Name
- Add a text field called Reference and mark it as Primary Field
- Delete the existing Title field
- Add a reference field called Wix Stores and connect it to the Products database
- Add a number field called Total Number of Stars and change the field key to stars
- Add a number field called Total Number of Reviews and change the field key to reviews
- Add a number field called Calculated Reviews
- Close the database collection and save your progress
At this point it is a good idea to Publish your site to get the database generated on your Wix dashboard.
Follow Along #2
Product Page: Add rating element and connect it to dataset
We will add a display rating element in the reviews section we previously designed. The video below has no audio. The video covers how to add and connect a rating element:
- Open the Product page within your editor
- Go to the Review section you previously designed
- Add a ratings display element to the page
- Make sure the ratings display attaches to the strip where your review section is located
- Toggle On the rating value and number of ratings settings
- Add a ratings label of your choice
- Add a placeholder text for when there are no reviews for any particular product
- Design and style the rating element as desired
- Add a dataset to the page and connect it to the Ratings collection
- Label your dataset
- Set the number of items to display as 1
- Connect the ratings element to the ratings dataset
- Connect the rating value to the Calculated Number field
- Connect the number of ratings to the Total Number of Reviews field
- Using the code panel rename the dataset element ID
- Review dataset ID used is viewRating
Follow Along #3
Product Page: Update the page with the new code
We have configured the code to match the new Ratings database collection we created. This code replaces the original code from the first tutorial entirely. Change the code as needed if your element ID's are different or if you modified your page further in anyway.
Our code basically checks if there are any existing rating calculations for product being browsed. If no matches are found, it will insert a rating calculation of 0 in the ratings database. If any matches are found, the code will do nothing further than filter the rating dataset to display to current numbers in the ratings database.
How is this different than Wix's tutorial? Instead of running a live calculation code we simply created a filter code to pull pre-calculated data to display it via the ratings element connected to the ratings dataset.
Why did we use this approach? We didn't want to live calculate a growing number of review records for each individual product. It is so much simpler to calculate the rating one time when the rating is being saved into the database instead of every single time the product page loads a new product. Continue to the next step to view the new calculation code for the lightbox that collects the reviews.
import wixData from 'wix-data';
import wixWindow from 'wix-window';
import wixLocation from 'wix-location';
let id;
let name;
let image;
let num = 0;
$w.onReady(function () {
$w('#productPage1').getProduct()
.then((product) => {
id = product._id;
name = product.name;
image = product.mainMedia;
//check if this product has any approved reviews
wixData.query("ReviewsSubmitted")
.eq("reference", id)
.eq("approved", true)
.find()
.then((results) => {
if (results.items.length > 0) {
$w('#repeater1').expand();
$w('#noReviews').collapse();
$w("#reviews").setFilter(wixData.filter()
.eq("reference", id)
.eq("approved", true)
)
.then(() => {
console.log("Dataset is now filtered");
let cq;
cq = "activated";
$w("#repeater1").onItemReady(($item, itemData) => {
let verified = itemData.verifiedPurchaser;
if (verified) {
$item("#verified").show();
}
});
})
.catch((err) => {
console.log(err);
});
} else {
console.log("This item has no reviews yet");
$w('#repeater1').collapse();
$w('#noReviews').expand();
}
})
.catch((error) => {
let errorMsg = error.message;
let code = error.code;
});
//check if this product has any rating calculations
wixData.query("Ratings")
.eq("reference", id)
.find()
.then((results) => {
if (results.items.length > 0) {
console.log("Ratings found, filtering dataset now.");
$w("#viewRating").setFilter(wixData.filter()
.eq("reference", id)
)
.then(() => {
console.log("Dataset is now filtered");
let cq;
cq = "activated";
})
.catch((err) => {
console.log(err);
});
} else {
console.log("This item has no ratings yet, creating blank entry now.");
let toInsert = {
"reference": id,
"productName": name,
"wixStores": id,
"stars": num,
"reviews": num,
"calculatedRating": num,
};
wixData.insert("Ratings", toInsert)
.then((results) => {
console.log("Entry complete.");
$w('#viewRating').refresh();
})
.catch((err) => {
let errorMsg = err;
});
}
})
.catch((error) => {
let errorMsg = error.message;
let code = error.code;
});
})
.catch((error) => {
console.error(error);
});
wixLocation.onChange((location) => {
let newPath = location.path;
//when the item changes we need to trigger the code again
$w('#productPage1').getProduct()
.then((product) => {
id = product._id;
name = product.name;
image = product.mainMedia;
//checking for reviews again
wixData.query("ReviewsSubmitted")
.eq("reference", id)
.eq("approved", true)
.find()
.then((results) => {
if (results.items.length > 0) {
$w('#repeater1').expand();
$w('#noReviews').collapse();
$w("#reviews").setFilter(wixData.filter()
.eq("reference", id)
.eq("approved", true)
)
.then(() => {
console.log("Dataset is now filtered");
})
.catch((err) => {
console.log(err);
let cq;
cq = "activated";
$w("#repeater1").onItemReady(($item, itemData) => {
let verified = itemData.verifiedPurchaser;
if (verified) {
$item("#verified").show();
}
});
});
} else {
console.log("This item has no reviews yet");
$w('#repeater1').collapse();
$w('#noReviews').expand();
}
})
.catch((error) => {
let errorMsg = error.message;
let code = error.code;
});
//checking if this product has any rating calculations
wixData.query("Ratings")
.eq("reference", id)
.find()
.then((results) => {
if (results.items.length > 0) {
console.log("Ratings found, filtering dataset now.");
$w("#viewRating").setFilter(wixData.filter()
.eq("reference", id)
)
.then(() => {
console.log("Dataset is now filtered");
let cq;
cq = "activated";
})
.catch((err) => {
console.log(err);
});
} else {
console.log("This item has no ratings yet, creating blank entry now.");
let toInsert = {
"reference": id,
"productName": name,
"wixStores": id,
"stars": num,
"reviews": num,
"calculatedRating": num,
};
wixData.insert("Ratings", toInsert)
.then((results) => {
console.log("Entry complete.");
$w('#viewRating').refresh();
})
.catch((err) => {
let errorMsg = err;
});
}
})
.catch((error) => {
let errorMsg = error.message;
let code = error.code;
});
})
.catch((error) => {
console.error(error);
});
});
});
export async function startReview_click(event, $w) {
const dataForLightbox = {
productId: id,
prodName: name,
prodPic: image,
};
let result = await wixWindow.openLightbox('review', dataForLightbox);
$w('#reviews').refresh();
}
Follow Along #4
Lightbox: Add ratings dataset and update with new code
Previously we created our custom review form on a lightbox. The following video has no audio. The video covers the following steps:
- Add a dataset to the lightbox and connect it to the Ratings collection
- Label your dataset
- Set the mode to Read and Write
- Set the number of items to display as 1
- Use the code panel to rename the dataset element ID
- Review dataset ID used is updateRating
We have configured new code to match the new Ratings database collection we created. This code replaces the original code from the first tutorial entirely. Change the code as needed if your element ID's are different or if you modified your page further in anyway.
What is different about this code? Now our code will calculate a new rating total before the review is saved into the database This keeps our rating calculations static and they only change when a new review is being saved into the database.
import wixWindow from 'wix-window';
import wixData from 'wix-data';
import { notifyAdmin } from 'backend/cqmail';
let productId;
let prodName;
let prodPic;
$w.onReady(function () {
productId = wixWindow.lightbox.getContext().productId;
prodName = wixWindow.lightbox.getContext().prodName;
prodPic = wixWindow.lightbox.getContext().prodPic;
$w('#prodName').text = prodName;
$w('#pic').src = prodPic;
$w('#saveReview').onAfterSave(async () => {
$w('#wait').hide();
$w('#reviewBox').collapse();
$w('#thankYouBox').expand();
setTimeout(() => {
wixWindow.lightbox.close();
}, 5000);
});
$w('#saveReview').onError(() => {
$w('#wait').hide();
});
//calculate rating here and update existing record
$w("#updateRating").setFilter(wixData.filter()
.eq("reference", productId)
)
.then(() => {
console.log("Dataset of reviews has been filtered by current product.");
let cq;
cq = "activated";
})
.catch((err) => {
console.log(err);
});
$w("#submit").onClick((event) => {
$w('#wait').show();
let cq = "activated";
$w('#saveReview').setFieldValues({
reference: productId,
wixStores: productId,
productName: prodName
});
$w("#saveReview").save()
.then((confirm) => {
//calculate rating here and update existing record
let confirmed = confirm.numberOfStarsRated; //see item below
console.log(confirmed);
//calculate rating here and update existing record
const currentrating = $w("#updateRating").getCurrentItem();
const stars = currentrating.stars;
const reviews = currentrating.reviews;
const toadd = Number(confirmed);
const newRatingLong = (stars + toadd) / (reviews + 1);
const newRatingShort = Number.parseFloat(newRatingLong).toFixed(1);
$w('#updateRating').setFieldValues({
'calculatedRating': Number(newRatingShort),
'stars': (stars + toadd),
'reviews': (reviews + 1)
});
$w("#updateRating").save()
.then((current) => {
notifyAdmin();
})
.catch((err) => {
let errMsg = err;
});
})
.then((current) => {
notifyAdmin();
})
.catch((err) => {
let errMsg = err;
});
});
});






