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.

tip

It's recommended to use the Handlebars routes object to output the endpoint URL.

Example

<!-- sections/product-recommendations.html -->
<product-recommendations
data-url="{{routes.product_recommendations_url}}?section_id={{section.id}}&product_id={{product.id}}&limit=4"
>
<h2>{{title}}</h2>
{{#if (isTruthy recommendations.performed) and recommendations.products_count > 0}}
<ul>
{{#for recommendations.products as |product|}}
<li>
<a href="{{ product.url }}">
<img src="{{ image_url product.featured_image width=300 height=300 }}"/>
<p>{{ product.title }}</p>
<p>{{ money product.price }}</p>
</a>
</li>
{{/for}}
</ul>
{{/and}}
</product-recommendations>
{{#schema}}
{
"name": "Product recommendations"
}
{{/schema}}
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);
Was this article helpful to you?