Product recommendations
Product recommendations are a good way to show customers products that are related to, or often purchased with, the current product.
This gives customers visibility on products that may interest them, and potentially leads to an increase in sales for merchants.
In this tutorial, you'll learn how to show product recommendations in your theme.
Resources
To implement product recommendations, you'll use the following:
Implementing product recommendations
In this implementation, the section content builds the general display by looping through each product returned through the products attribute of the recommendations object.
This object isn’t populated when the section is initially rendered, so you need to use JavaScript to retrieve the populated section content through the section response of the Product Recommendations API.
It's recommended to use the Handlebars routes object
to output the endpoint URL.
Example
<!-- sections/product-recommendations.html -->
<product-recommendations
data-url="?section_id=&product_id=&limit=4"
>
<h2></h2>
<ul>
<li>
<a href="">
<img src=""/>
<p></p>
<p></p>
</a>
</li>
</ul>
</product-recommendations>
{
"name": "Product recommendations"
}
class ProductRecommendations extends HTMLElement {
connectedCallback() {
const initRecommendation = (entries, observer) => {
if (!entries[0].isIntersecting) return;
observer.unobserve(this);
fetch(this.dataset.url)
.then((response) => response.text())
.then((text) => {
const elem = document.createElement('div');
elem.innerHTML = text;
const recommendations = elem.querySelector('product-recommendations');
if (recommendations && recommendations.innerHTML.trim().length) {
this.innerHTML = recommendations.innerHTML;
}
})
.catch((err) => {
console.error('[product recommedations - error]', err);
});
};
new IntersectionObserver(initRecommendation.bind(this), {
rootMargin: '0px 0px 350px 0px',
}).observe(this);
}
}
customElements.define('product-recommendations', ProductRecommendations);