Search code examples
shopifyproductliquidshopify-template

How to add an add to cart button on products displayed on product recommendation section in shopify?


i'm using dawn theme, and i tried adding button to the product-card.liquid file, here the code..

{% for image in product.images limit:1 %}
   <a href="{{ product_card_product.url | default: '#' }}">
     <img src="{{ product_card_product.featured_media | img_url: '533x' }}" />
   </a>
{% endfor %}    
<form method="post" action="/cart/add" style="text-align: center">
     <input type="hidden" name="id" value="{{ product.variants.first.id }}" />
       <button type="submit" class="addCart" {% unless product.available %} disabled="disabled" {% endunless %}>
       {% unless product.available %}
           {{ "products.product.sold_out" | t }}
       {% else %}
           {{ "products.product.add_to_cart" | t }}
       {% endunless %}
       </button>
    </form>

so what happens is, this particular section is in product page, and by clicking on add to cart button, this adds up that particular product page's product, which already has a dedicated button and doesn't add the product which is recommended.. i tried printing the product.variants.first.id object beside add to cart, and this id is same for all the products recommended.. i have checked all the for loops and everythings closed and proper..


Solution

  • Use product_card_product as object instead of product

      <form method="post" action="/cart/add" style="text-align: center">
        <input type="hidden" name="id" value="{{ product_card_product.variants.first.id }}" />
        <button type="submit" class="addCart" {% unless product_card_product.available %} disabled="disabled" {% endunless %}>
          {% unless product_card_product.available %}
          {{ "products.product.sold_out" | t }}
          {% else %}
          {{ "products.product.add_to_cart" | t }}
          {% endunless %}
        </button>
      </form>