Solved

Exclude product from product recommendations

witmade
Shopify Partner
17 1 5

I have Route Shipping Insurance installed on a couple of stores. How do I exclude the Route Insurance product from Product Recommendations on my Product pages?

Screen Shot 2020-08-03 at 3.53.38 PM.png

Currently in an unpublished theme: https://kcee3o3v9odpjwyb-10257858615.shopifypreview.com

 

Here is my liquid for that section:
"

 
<div class="product-recommendations" data-product-id="{{ product.id }}" data-limit="3">  {%- if recommendations.products_count > 0 -%}
  <div class="product-recommendations-pannel">
    <h2>You may also like</h2>
    <ul>
      {%- for product in recommendations.products -%}
      <li class="product">
        <a href="{{ product.url }}">
          <img class="product__img" src="{{ product.featured_image | img_url: '300x300' }}" alt="{{ product.featured_image.alt }}" />
          <p class="product__title">{{ product.title }}</p>
          <p class="product__price">{{ product.price | money}}</p>
        </a>
      </li>
      {%- endfor -%}
    </ul>
  {%- endif -%}
  </div>
</div>
 
<style>
.product-recommendations-pannel h2 {
    text-align: center;
    margin-bottom: 40px;
}
.product-recommendations-pannel ul {
   display:flex;
  justify-content: space-around;
.product-recommendations-pannel ul>li {
  text-align:center;
.product-recommendations-pannel {
    padding: 60px;
    background: #F0E2CD;
}
  .product-recommendations-pannel ul>li {
    text-align: center;
    width: 33%;
}
 
     @media(max-width:767px){
  .product-recommendations-pannel ul>li {
    width: 100% !important;
        margin-bottom: 40px;
}
    .product-recommendations-pannel ul {
    display: inherit !important;
    justify-content: normal;
}
    p.product__title {
    margin-bottom: 0;
}
.product-recommendations-pannel ul>li:last-child {
    text-align: center;
    width: 33%;
    margin-bottom: 0;
}
    
 
    
    
  } 
</style> 
<script>
  
 
var loadProductRecommendationsIntoSection = function() {
  // Look for an element with class 'product-recommendations'
  var productRecommendationsSection = document.querySelector(".product-recommendations");
  if (productRecommendationsSection === null) { return; }
  // Read product id from data attribute
  var productId = productRecommendationsSection.dataset.productId;
  // Read limit from data attribute
  var limit = productRecommendationsSection.dataset.limit;
  // Build request URL
  var requestUrl = "/recommendations/products?section_id=product-recommendations&limit="+limit+"&product_id="+productId;
  // Create request and submit it using Ajax
  var request = new XMLHttpRequest();
  request.open("GET", requestUrl);
  request.onload = function() {
    if (request.status >= 200 && request.status < 300) {
      var container = document.createElement("div");
      container.innerHTML = request.response;
      productRecommendationsSection.parentElement.innerHTML = container.querySelector(".product-recommendations").innerHTML;
    }
  };
  request.send();
};
// If your section has theme settings, the theme editor
// reloads the section as you edit those settings. When that happens, the
// recommendations need to be fetched again.
document.addEventListener("shopify:section:load", function(event) {
  if (event.detail.sectionId === "product-recommendations") {
    loadProductRecommendationsIntoSection();
  }
});
// Fetching the recommendations on page load
loadProductRecommendationsIntoSection();
 
  
  
  
  
</script>
 
 
{% schema %}
  {
    "name": "Section name",
    "settings": []
  }
{% endschema %}
 
{% stylesheet %}
{% endstylesheet %}
 
{% javascript %}
{% endjavascript %}"
 

Thank you!

Accepted Solution (1)
diego_ezfy
Shopify Partner
2934 562 883

This is an accepted solution.

Hello, 

The script is basically hiding that specific product, so you'd need to set the value to "4" to display another one.

To develop a solution to completely discard the product it would require me to be within your theme to edit the liquid files and create the appropriate code. 

Unfortunately not an entirely flawless solution but this is the best I can do without being in your store.

Kind regards, 

Diego

◦ I can help you further! Top #4 Shopify Expert, 24h reply. Click here to hire me.
◦ Follow my blog & youtube for more free coding tips.
Download copy/paste code snippets that can replace most apps.

View solution in original post

Replies 8 (8)

diego_ezfy
Shopify Partner
2934 562 883

1. In your Shopify Admin go to online store > themes > actions > edit code
admin-page.png
2. In your theme.liquid file, find the </body> (press CTRL + F or command + F on Mac)
3. paste this code right above the </body> tag:

<script>
function removeRouteShippingProduct(){
	const isProductPage = /product/.test(window.location.href);
	const product = document.querySelector(`.template-product .product-recommendations-pannel [href*='/products/routeins']`);

	if (!product || !isProductPage){
		return;
	}
	
	product.closest(`.product`).classList.add('routein-product');
	product.closest(`.product`).remove();
	
}
document.addEventListener("DOMContentLoaded", function() {
  setTimeout(removeRouteShippingProduct, 100);
	});
</script>
<style>
.routein-product,
[href*='products/routeins']{
	display: none !important;
}
</style>


Please let me know whether it works.

Kind regards,
Diego

◦ I can help you further! Top #4 Shopify Expert, 24h reply. Click here to hire me.
◦ Follow my blog & youtube for more free coding tips.
Download copy/paste code snippets that can replace most apps.

witmade
Shopify Partner
17 1 5

Hi, 

Thank you for the suggestion. It worked, kind of. The script did hide route insurance by now instead of 3 recommended products displaying, only 2 are displaying (see screenshot). The products-recommendations.liquid file I have specifies displaying 3 and that is how the section is designed
so ideally it should display 3, just not route 🙂 Thank you!

Screen Shot 2020-08-03 at 9.00.31 PM.png

diego_ezfy
Shopify Partner
2934 562 883

This is an accepted solution.

Hello, 

The script is basically hiding that specific product, so you'd need to set the value to "4" to display another one.

To develop a solution to completely discard the product it would require me to be within your theme to edit the liquid files and create the appropriate code. 

Unfortunately not an entirely flawless solution but this is the best I can do without being in your store.

Kind regards, 

Diego

◦ I can help you further! Top #4 Shopify Expert, 24h reply. Click here to hire me.
◦ Follow my blog & youtube for more free coding tips.
Download copy/paste code snippets that can replace most apps.

n_bcn
Excursionist
18 1 1

Hello,

I tried the above and I am having the same trouble with it just hiding the Route item from the grid but not replacing it.

The section should display 4 items on both desktop and mobile, so I guess I need to set the value to 5? Could you please tell me how to do this as I can't figure it out? I'm using debut theme for my store and the product-recommendations.liquid code is as follows:

{%- if section.settings.show_product_recommendations -%}
  {%- if recommendations.performed -%}
    {%- if recommendations.products_count > 0 -%}
      <div class="product-recommendations">
        <div class="section-header text-center">
          {%- if section.settings.heading != blank -%}
            <h2 class="h1 section-header__title">{{ section.settings.heading | escape }}</h2>
            <hr class="hr--small">
          {%- endif -%}
        </div>
        <div class="grid-uniform">
          {% assign grid_item_width = 'small--one-half medium--one-half large--one-quarter' %}
          {%- for product in recommendations.products -%}
            {% include 'product-grid-item-2' %}
          {%- endfor -%}
        </div>
      </div>
    {%- endif -%}
  {%- else  -%}
    <div 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 -%}

{% schema %}
{
  "name": {
    "da": "Produktanbefalinger",
    "de": "Produktempfehlungen",
    "en": "Product recommendations",
    "es": "Recomendaciones de productos",
    "fi": "Tuotesuositukset",
    "fr": "Recommandations de produits",
    "hi": "उत्पाद की अनुशंसाएं",
    "it": "Raccomandazioni sui prodotti",
    "ja": "商品の推奨",
    "ko": "제품 권장 사항",
    "nb": "Produktanbefalinger",
    "nl": "Productaanbevelingen",
    "pt-BR": "Recomendações de produtos",
    "pt-PT": "Recomendações de produtos",
    "sv": "Produktrekommendationer",
    "th": "คำแนะนำสินค้า",
    "zh-CN": "产品推荐",
    "zh-TW": "商品推薦"
  },
  "settings": [
    {
      "type": "checkbox",
      "id": "show_product_recommendations",
      "label": {
        "da": "Vis dynamiske anbefalinger",
        "de": "Dynamische Empfehlungen anzeigen",
        "en": "Show dynamic recommendations",
        "es": "Mostrar recomendaciones dinámicas",
        "fi": "Näytä dynaamiset suositukset",
        "fr": "Afficher les recommandations dynamiques",
        "hi": "डायनेमिक सुझाव दिखाएं",
        "it": "Mostra raccomandazioni dinamiche",
        "ja": "動的推奨を表示する",
        "ko": "동적 권장 사항 표시",
        "nb": "Vis dynamiske anbefalinger",
        "nl": "Dynamische aanbevelingen weergeven",
        "pt-BR": "Exibir recomendações dinâmicas",
        "pt-PT": "Mostrar recomendações dinâmicas",
        "sv": "Visa dynamiska rekommendationer",
        "th": "แสดงคำแนะนำแบบไดนามิก",
        "zh-CN": "显示动态推荐",
        "zh-TW": "顯示動態推薦"
      },
      "info": {
        "da": "Dynamiske anbefalinger ændres og forbedres med tiden. [Få mere at vide](https://help.shopify.com/en/themes/development/recommended-products)",
        "de": "Dynamische Empfehlungen werden im Laufe der Zeit angepasst und verbessert. [Mehr Informationen](https://help.shopify.com/en/themes/development/recommended-products)",
        "en": "Dynamic recommendations change and improve with time. [Learn more](https://help.shopify.com/en/themes/development/recommended-products)",
        "es": "Las recomendaciones dinámicas cambian y mejoran con el tiempo. [Más información](https://help.shopify.com/en/themes/development/recommended-products)",
        "fi": "Dynaamiset suositukset muuttuvat ja paranevat ajan myötä. [Lisätietoja](https://help.shopify.com/en/themes/development/recommended-products)",
        "fr": "Les recommandations dynamiques changent et s'améliorent avec le temps. [En savoir plus](https://help.shopify.com/en/themes/development/recommended-products)",
        "hi": "समय के साथ डायनेमिक सुझाव परिवर्तन और सुधार. [अधिक जानें](https://help.shopify.com/en/themes/development/recommended-products)",
        "it": "Le raccomandazioni dinamiche cambiano e migliorano nel tempo. [Maggiori informazioni](https://help.shopify.com/en/themes/development/recommended-products)",
        "ja": "動的推奨は時間とともに変化し改善します。[詳しくはこちら](https://help.shopify.com/en/themes/development/recommended-products)",
        "ko": "동적 권장 사항은 시간이 지나면서 변하고 개선됩니다. [자세히 알아보기](https://help.shopify.com/en/themes/development/recommended-products)",
        "nb": "Dynamiske anbefalinger endrer seg og forbedres med tiden. [Finn ut mer](https://help.shopify.com/en/themes/development/recommended-products)",
        "nl": "Dynamische aanbevelingen veranderen en verbeteren mettertijd. [Meer informatie](https://help.shopify.com/en/themes/development/recommended-products)",
        "pt-BR": "As recomendações dinâmicas mudam e melhoram com o tempo. [Saiba mais](https://help.shopify.com/en/themes/development/recommended-products)",
        "pt-PT": "As recomendações dinâmicas mudam e melhoram com o tempo. [Saiba mais](https://help.shopify.com/en/themes/development/recommended-products)",
        "sv": "Dynamiska rekommendationer ändras och förbättras med tiden. [Läs mer](https://help.shopify.com/en/themes/development/recommended-products)",
        "th": "คำแนะนำแบบไดนามิกนั้นเปลี่ยนแปลงและถูกปรับปรุงให้ดีขึ้นตลอดเวลา [ดูข้อมูลเพิ่มเติม](https://help.shopify.com/en/themes/development/recommended-products)",
        "zh-CN": "动态推荐会随着时间而变化和改进。[了解详细信息](https://help.shopify.com/en/themes/development/recommended-products)",
        "zh-TW": "動態推薦會隨著時間改變與改進。[深入瞭解](https://help.shopify.com/en/themes/development/recommended-products)"
      },
      "default": true
    },
    {
      "type": "text",
      "id": "heading",
      "label": {
        "da": "Overskrift",
        "de": "Überschrift",
        "en": "Heading",
        "es": "Título",
        "fi": "Otsake",
        "fr": "En-tête",
        "hi": "शीर्षक",
        "it": "Heading",
        "ja": "見出し",
        "ko": "제목",
        "nb": "Overskrift",
        "nl": "Kop",
        "pt-BR": "Título",
        "pt-PT": "Título",
        "sv": "Rubrik",
        "th": "ส่วนหัว",
        "zh-CN": "标题",
        "zh-TW": "標題"
      },
      "default": {
        "da": "Du vil muligvis også synes om",
        "de": "Das könnte dir auch gefallen",
        "en": "You may also like",
        "es": "También te puede interesar",
        "fi": "Saatat pitää myös näistä",
        "fr": "Vous pourriez aimer également",
        "hi": "आप शायद इसे भी पसंद करें",
        "it": "Potrebbero interessarti anche",
        "ja": "あなたへのおすすめ",
        "ko": "회원님도 좋아할 것입니다.",
        "nb": "Kanskje du også liker",
        "nl": "Wellicht vind je dit ook leuk",
        "pt-BR": "Talvez você também goste de",
        "pt-PT": "Também poderá gostar de",
        "sv": "Du kanske också gillar",
        "th": "คุณอาจจะชอบ",
        "zh-CN": "您可能还喜欢",
        "zh-TW": "您也可能喜歡"
      }
    }
  ]
}
{% endschema %}

Thanks!

Nina

TheGoodMarkCo
Visitor
2 0 1

Can I ask how you knew his product was titled "routine" and knew to use that in the code? 

I think I can understand and manipulate this code to work but I don't know what the product is actually called in the backend of my page. The do you got for this info?

Thank you!

ElliottLM
Tourist
4 0 1

Put ".json" at the end of the url for the product page of the product. You can then format this online by searching for json formatter or use your IDE and a formatter extension.

ICR8
Visitor
1 0 0

 I saw where you have answered this. One question I have is that we have a few products do we not want to see. Would we have to do this for every product we do not want to show? Thanks.

smj_90
Shopify Partner
54 1 15

Hi there, loved your solution,

any idea how to fix the same in Dawn 2.0?

If this helped you, please
mark this reply as 'Accepted Solution'
Thanks 🙂