How to use a product metafield with json value in your BigCommerce stencil theme


Discover the magic of incorporating product metafields into your BigCommerce Stencil theme with our detailed guide.

In this tutorial, we’ll walk you through the process, focusing on the addition of a size guide stored in a product metafield as JSON, to your product detail page.

Our metafield looks like this:

{
  "id": 44,
  "key": "size-guide",
  "value": "[{\"id\":18,\"name\":\"Children's\",\"heading\":\"Children's size guide\",\"details\":\"<table class=\\\"cms_sizing\\\">\\n<tbody>\\n<tr>\\n<th>Size</th>\\n<th>Height</th>\\n<th>Shoulder<br>to Hem</th>\\n<th>Body Change<br>Space</th>\\n</tr>\\n<tr>\\n<td>5-9 Years</td>\\n<td>100 - 135cm<br>(3'3\\\" - 4'4\\\")</td>\\n<td>70cm</td>\\n<td>62cm</td>\\n</tr>\\n<tr>\\n<td>10-14 Years</td>\\n<td>135 - 150cm<br>(4'4\\\" - 4'9\\\")</td>\\n<td>84cm</td>\\n<td>75cm</td>\\n</tr>\\n</tbody>\\n</table>\"}]",
  "namespace": "shared",
  "permission_set": "write_and_sf_access",
  "resource_type": "product",
  "resource_id": 113,
  "description": "",
  "date_created": "2024-01-03T10:59:19+00:00",
  "date_modified": "2024-01-08T14:40:23+00:00"
}

You can see that the value is a JSON string and when parsed will be a list with a single item in. This item is an object with id, name, heading and details properties.

This metafield was actually created using our Metafields Manager app so if you’re looking for an easier way to manage content in metafields, check that out.

So let’s take a look at how we can integrate metafields into your stencil theme to enrich product pages.

Fetching metafields with GraphQL

To start, let’s fetch the metafield using the storefront GraphQL API.

Our product metafield can be fetched with the following GraphQL query:

query productById($productId: Int!) { 
  site { 
    product(entityId: $productId) {
      metafields(namespace: \"shared\", keys: [\"size-guide\"]) {
        edges {
          node {
            id
            key
            value
          }
        }
      }
    } 
  }
}

We only wish to fetch the “shared.size-guide” metafield, so we have filtered the product metafields by the “shared” namespace and then the “size-guide” is the single entry in the keys array.

If you need to query metafields from namespaces in a single query, then you can use multiple metafield queries using GraphQL aliases.

To save you the job of crafting the GraphQL query, our Metafields Manager app provides a “View GraphQL” option to generate it for you.

Now, you’re ready to make a request to the storefront GraphQL API. We’re going to do so “server-side” using Stencil’s support for adding a GraphQL query to a template’s front matter.

Adding GraphQL Query to Front Matter

All top level page templates in BigCommerce support the inclusion of a storefront GraphQL query. This query will be processed before the rendering of the page template, making the results available to theme developers within the theme itself without the need for client-side AJAX request.

In our example, we want to add our size guide to the product page, so we open the template/pages/product.html file and update the front matter with an additional gql section. We must ensure we replace any double quotes within the query with single quotes.

--- 
product: 
  videos:
    limit: {{theme_settings.productpage_videos_count}}
  reviews:
    limit: {{theme_settings.productpage_reviews_count}}
  related_products:
    limit: {{theme_settings.productpage_related_products_count}}
  similar_by_views:
    limit: {{theme_settings.productpage_similar_by_views_count}}
gql: "query productById($productId: Int!) {
  site { 
    product(entityId: $productId) {
      metafields(namespace: \"shared\", keys: [\"size-guide\"]) {
        edges {
          node {
            id
            key
            value
          }
        }
      }
    }
  }
}
"
---

When you’re using stencil development server, you can add the query param: ?debug=bar which will append the current context to the end of the page. This shows all the data that’s available in variables for customising the response.

Assuming our GraphQL query is valid, the result will now be shown in the debug section – given clarity on how it can be accessed.

Note that storefront GraphQL queries can only be added to page templates and cannot be added to components. To use the data in components, you will need to pass the information down into the partials as an argument.

Using the GraphQL response in a template

With the metafield data in hand, it’s time to display it on your product page. The first step we might take is to loop through each of the nodes, and filter based on the metafield key i.e. ‘size guide’.

{{#each gql.data.site.product.metafields.edges }}
  {{#if node.key '===' 'size-guide'}}
    {{json node}}
  {{/if}}
{{/each}}

If all steps have been completed correctly, the {{json node}} debug line will print out the metafield we’re interested in.

We can then proceed to the next step which is to use the metafield value. In our case, our value is JSON which we wish to parse. This can be performed using the JSONparse handlebars helper. This will change parse the JSON and replace the current context with that of the parsed data. The current context is accessible using this, ..

Let’s update our template with the logic to parse, and then dump out the data again:

{{#each gql.data.site.product.metafields.edges }}
  {{#if node.key '===' 'size-guide'}}
    {{#JSONparse node.value}}
      {{json .}}
    {{/JSONparse}}
  {{/if}}
{{/each}}

Ok, we can now complete our task by using our parsed metafield data to display our size guide.

{{#each gql.data.site.product.metafields.edges }}
  {{#if node.key '===' 'size-guide'}}
    {{#JSONparse node.value}}
      {{#withFirst .}}
        <h4>{{heading}}</h4>
        {{{details}}}
      {{/withFirst}}
    {{/JSONparse}}
  {{/if}}
{{/each}}

By following these steps, you can seamlessly integrate a product metafield, like a size guide, into your Stencil theme’s product detail page using GraphQL. Enhance your BigCommerce store’s customization and provide valuable information to your customers. Experiment with different metafields to tailor your store to meet your unique needs.

Tom Robertshaw
Stay up to date with Hypa news and features