0
votes

I want to create metafield every time when my shopify customer subscribe to product on my shopify store so i got following code to create metafield but don’t know how it would work on liquid theme ? Can any one guide me where i need to write following code to make it functional ?

‘POST’, ‘/admin/products/1328/metafields.json’, array(“metafield” => 
array(‘namespace’=>’inventory’, ‘key’=>’warehouse’, ‘value’=>"some text here",   ‘value_type’=>’string’)));

How can i make above code in liquid templating pages to create a metafield using shopify api ?

4
And i found another example and tried product = ShopifyAPI::Product.find(148362461) product.add_metafield(ShopifyAPI::Metafield.new({ :description => 'Developer of the Site', :namespace => 'chargify', :key => 'customer', :value => 'Metlo', :value_type => 'string' })) It also didn't work, i need to know how can i create / update / delete a metafield on customers account page on shopify ?Naveed Metlo

4 Answers

1
votes

You cannot create a metafield in liquid. If you want to create metafields, you must use admin API / graphQL API to do so.

Liquid only allows you to "print" existing data to the template.

0
votes

Pure liquid "interacted" by visitor of your store, won't be allowed to do anything with the Shopify API. You need to have an Oauth open session in order to post / read your store data.

0
votes

For your example you would reference the meta field in this way.

{{ product.metafields.inventory.warehouse }}

that would then show

"some text here"

0
votes

In order to do this, you need to make a controller and method that will receive an AJAX request and make a call to the Shopify API.

Create click event on the product subscription button. Click event will look like this:

let url = 'https://your_host.com/your_contoller/your_method?shop=your_shop_domain';
let postData = { product_id: "your_product_id" };
$.ajax({
  type: 'post',
  url: url,
  data: postData,
  dataType: 'json',
  complete: (res) => {
      console.log(res); // response from your_method
  }
});

In the controller method, you must use the Shopify client as phpish/shopify or any other. With the client using api_key, access_token of your app or private app, you can make this kind of request:

POST /admin/api/2020-10/products/PRODUCT_ID/metafields.json
{
  "metafield": {
    "namespace": "inventory",
    "key": "warehouse",
    "value": 25,
    "value_type": "integer"
  }
}

After you should get back the result.

But if you want to create metafields on request from your customer, it's better to wrap controller method in a queue and use the queues, because if you don't use the queues there's a chance to fall within the limit of Shopify REST API.

After create a metafield, you can get value from liquid with code from Richard.