skip to Main Content

I created a "Product Reference" and "List of products" metafield. This allows me to add multiple products into the metafield that I made. What I’m trying to do is display images and titles of the products that I added but what I would like to do is able to access each of the products I added.
enter image description here

For example, I have added two products to my metafield section but I only want to display one of them on my product page.
enter image description here

The reason why I would like to access my products individually is I’m going to use bootstrap and I want to add each product picture individually to the divs I created.

Here’s what my code looks like when I’m trying to call my metafield. (It brings both of the pictures)

   {% if product.metafields.my_fields.custom_img.value != blank  %}

    <h3>Recommended Products</h3>
    
    {% assign recommended_products = product.metafields.my_fields.custom_img.value %}
    {% for product in recommended_products  %}     
    
      <a href="{{ product.url }}">
        {{ product.featured_image | image_url: width: 400 | image_tag }}
        
      </a>
   
    {% endfor %}

   {% endif %}

2

Answers


  1. If you want to display only the first the easiest way is to do

    {% for product in recommended_products limit: 1  %}     
     <div> ... </div>
    
    {% endfor %}
    

    Or if you want to display a particular product

    {% for product in recommended_products  %}     
    
      {% if product.title == "title"  %}
        <div> ... </div>    
        {% break %}
      {% endif %}
    {% endfor %}
    

    If you want to have more control over the for cylce liquid offers you the forloop object https://shopify.dev/api/liquid/objects/for-loops

    For example you could also do

    {% for product in recommended_products  %}     
     <div>... </div>
     {% if forloop.index0 > 1 %}
        {% break %}
      {% endif %}
    {% endfor %}
    

    to display the first 2 products.

    Login or Signup to reply.
  2. You can access the metafield that you’ve created just like any list in liquid, for example, if you want to access the first product in the list you can do

    {% assign first_product = product.metafields.my_fields.custom_img.value | first %}
    

    Or you can access any specific product in the list like so:

    {% comment % }Access second product {% endcomment %}
    {% liquid
      assign second_product = product.metafields.my_fields.custom_img.value[1]
      if second_product != blank
        echo '<h1>second_product.title</h1>'
      endif
    %}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search