badmintonbolden
badmintonbolden

Reputation: 13

How to work with product meta field in Shopify?

I have created a custom meta field for blog posts in Shopify. It's of the type product and I have chosen List of products.

I want to loop through the products and render them using the theme's product-grid-item template.

My problem is, that the type of my meta field output is a string - not an array.

If i try to output the field like this {{ article.metafields.blog_post.feature_products }}

I get the following: ["gid://shopify/Product/8078688583991","gid://shopify/Product/8078688715063","gid://shopify/Product/8078689141047"]

Which looks like an array, but liquid sees it as a string.

I have tried to loop through it like the following. But nothing happens

{% for product_id in article.metafields.blog_post.feature_products %}   
  {{ product_id }} 
{% endfor %}

It feels like I'm missing something obvious. It doesn't make sense, that the output is a string.

Does anybody know how to output it like an array? Or how to convert the string to an array - without the quote-marks, brackets and so on.

Upvotes: 1

Views: 1368

Answers (1)

Geneviève M.
Geneviève M.

Reputation: 260

For metafields that allow multiple values, the list of values is stored in the value property of the metafield. Add .value at the end of your loop statement.

Note that your product_id variable will be a product object. I suggest you rename it to "product". You can then access the id (and other properties) using the dot notation.

{% for product in article.metafields.blog_post.feature_products.value %}   
  {{ product.id }} 
{% endfor %}

Upvotes: 2

Related Questions