Create and retrieve metafield for shop resource in shopify

Create and retrieve metafield for shop resource in shopify

This is a quick guide to create and retrieve metafield for shop resource in shopify using ruby on rails.

Just a reminder, shop resource in shopify is a global resource for the shopify store and metafield associated with shop resource is accessible throughout the store. Once this metafield is associated with your shopify store you can access it on any liquid files.

This post assume that you have a clear understanding of Ruby on Rails , use of shopify_app gem and how to create shopify app in rails. If you are new to creating shopify app please refer to this link . You can skip the detail in the link above and jump to the video at the bottom. It is the quick tutorial that will help you to get your first default application up and running in few minutes.

Actually to create and retrieve metafield for shop resource in shopify is quite easy if you use the shopify_app gem.

So let’s get started.

Below code snippet show both create and access of the metafield for shop resource. I will describe the code below.

So let’s understand what it does.

The first line shows a controller class which extend the ShopifyApp::AuthenticatedController , to use shopify resource from rails app you need to extend this controller. You will learn about this in detail in the video in the link above.

I have used create method to create the metafield for shop resource in shopify. First thing we need to data to be stored in the metafield which I am getting from a post request.
You need the shop object in which you will create the metafield. This resource can be accessed by

Now you can create the metafield over this shop resource. Below code does this

You can add the description, namespace and key on your own. The value for namespace and key are used to access this value in the frontend or elsewhere. The value field will hold the value for the metafield.

Accessing the metafield for shop resource in shopify is similar. Below code will achieve this

I have added necessary comments on the code for understanding it better.

Using above code you can now easily create and retrieve metafield for shop resource in shopify.

Hope this stand useful for you.