I want to add product recommendations on my shopify cart page.
I have added:
{% section 'product-recommendations' %}
in the cart.liquid
file.
This file consists of:
{%- if section.settings.show_product_recommendations -%}
{%- if recommendations.performed -%}
{%- if recommendations.products_count > 0 -%}
<div class="product-recommendations__inner">
{%- if section.settings.heading != blank -%}
<div class="section-header">
<h2>{{ section.settings.heading | escape }}</h2>
</div>
{%- endif -%}
<ul data-slides="8" id='product-slider' class="grid grid--uniform grid--view-items product-slider">
{%- for product in recommendations.products -%}
<li class="grid__item small--one-half medium-up--one-quarter">
{% include 'product-card-grid', max_height: 250, product: product, show_vendor: section.settings.show_vendor %}
</li>
{%- endfor -%}
</ul>
</div>
{%- endif -%}
{%- else -%}
<div class="page-width recommendations-container" data-base-url="{{ routes.product_recommendations_url }}" data-product-id="{{ product.id }}" data-section-id="{{ section.id }}" data-section-type="product-recommendations"></div>
{%- endif -%}
{%- endif -%}
It is being inserted into the page (I can see the container), but nothing actually renders other than the container margin/padding. I suspect its because I’m not on a product page.
How would I make this work on the cart page?
2
Answers
The reason why it did not work was same that you concluded, that it was not a product page. However, given the product ID we can get the recommendations of any product. The Shopify Docs for Recommendations object state
So, unlike Shopify product page, where product object is globally available, you have to pass product ID from Shopify cart items. To do so, add a new section named product-recommendations-cart and include it in your cart template.
Then inside product-recommendations-cart section
Here, I added the condtion to display only if cart has some items and used the last product in cart to get recommendations.
As per your comment, I have added the condition to skip products that are already in cart. You can improve this using a string of product ids in cart instead of looping all cart items again and again.
If you need more control, use Product recommendations with the Product Recommendations API products response.
You can also create a cart recommendations using jQuery.
Here I added the jQuery code. In this ajax call response you will get the recommendations product JSON.
Instead of item.product_id you can use your cart item id and instead of custom-cart you can add you section name where you html is created.