I have a code that will output 3 products within a set price range onto my products page in my shop. I have a few issues though,
- The item shown on the product page can still appear within the 3 product output query and i do not wish this to happen.
- The same items are showing up alot in the output, i need it to be more random but still within the set price range.
- When products are outputted from the function and clicked on i need the function to start again and display a different set of products every time.
I have put the code below and would really appreciate some help with this.
import wixData from ‘wix-data’;
import wixLocation from ‘wix-location’;
// For full API documentation, including code examples, visit http://wix.to/94BuAAs
$w.onReady( function () {
loadRelatedProducts();
});
async function loadRelatedProducts() {
let product = await $w(‘#productPage’).getProduct();
let relatedProductsResult = await relatedProductsByPrice(product);
showRelatedProducts(relatedProductsResult);
}
async function relatedProductsByPrice(product) {
let productId = product._id;
let relatedByPrice = await wixData.query(‘Stores/Products’)
.between(‘price’, product.price * 0.6, product.price * 1.3)
.ne(‘_id’, productId)
.find();
return relatedByPrice.items;
}
function showRelatedProducts(relatedProducts) {
if (relatedProducts.length > 0) {
relatedProducts.splice(3, relatedProducts.length);
$w(‘#relatedItemsRepeater’).onItemReady(relatedItemReady);
$w(‘#relatedItemsRepeater’).data = relatedProducts;
$w(‘#retatedItems’).expand();
} else {
$w(‘#retatedItems’).collapse();
}
}
function relatedItemReady($w, product) {
$w(‘#productImage’).src = product.mainMedia;
$w(‘#productName’).text = product.name;
$w(‘#productPrice’).text = product.formattedPrice;
$w(‘#productImage’).onClick(() => {
wixLocation.to(product.productPageUrl);
})
}