Shamon S
Shamon S

Reputation: 145

How to fetch product metafields in cart.js Shopify

How do I get product meta fields in Shopify store cart.js response?

Currently, In cart.js not providing any details of product metafields.

Upvotes: 3

Views: 4746

Answers (6)

pooja saini
pooja saini

Reputation: 1

{%- if item.product.metafields.my_fields.minimum_order_quantity != blank -%}  
    {{ item.product.metafields.my_fields.minimum_order_quantity }}                                        
{%- endif -%}

Use this code and show data on cart page

Upvotes: 0

Ayushi lasod
Ayushi lasod

Reputation: 11

** You can do this by adding the following step**

  1. Add the below code in product form

{% for field in product.metafields.namespace%}
             <input required class="required hidden" id="customID" type="hidden" value='{{ field | last }}' name="properties[metafields[{{ field | first }}]]"> 
    {% endfor %}

  1. it will add in your cart object you can access it by

{% for field in item.properties.metafields %}
         {{ field | first }}: {{ field | last }}
    {% endfor %}

Upvotes: 1

pensebien
pensebien

Reputation: 554

You can get the metafields content of the appropriate products, collections, orders by assigning it to a variable in the liquid file. In the product-template.liquid, you can use

   {% assign var_meta = page.metafields.meta_namespace %} 

// You can use the Shopify docs to understand how you create Metafields

   {% assign key = 'meta_key' %}
   {% assign key_val_meta = meta_namespace.meta_key %}

Access the variable {{key_val_meta}}

If you assign unique values to the metafield, you could use it to get the exact information you can input that information in your cart.js function.

Upvotes: 0

Eric NEMO
Eric NEMO

Reputation: 539

You have many possible hack. The one I would recommend if you are using CartJS is

  1. In your product page, print the product metafield in the HTML

    <div class="product-page" data-metafield="{{product.metafield.namespace.value}}">
    </div>
    
  2. When product is added, simply add the metafield as a line item property

    var properties = {metafield : $('.product-page').data('metafield')}; CartJS.addItem(variantId, 1 ,properties);

  3. The metafield is now accessible at CartJS.cart.items[i].properties[metafield] !

Upvotes: 2

yosh
yosh

Reputation: 11

You can access the metafield using item.product.metafields.your-namespace.your-key.

Upvotes: 0

David Lazar
David Lazar

Reputation: 11427

Metafields are available client-side via Liquid. You do not need cartJS to fetch them. You can render the product metafields of interest into your own data structure of choice, and use the as you wish anyway you want.

You could also build out a StorefrontAPI based system and try GraphQL if you're really keen.

Upvotes: 0

Related Questions