Accessing metafields on storefront in BigCommerce

Viewed 362

I'm currently working on a solution where I need to extend Product information with additional (custom) data. I chose to store it in metafields as they may be more complex than a simple custom field (limit to 250 chars) plus they need to be readonly for admin personell. I want to access these fields in the storefront template.

I see that there's a permission option for metafiels read_and_sf_access (setting storefront access for the metafield) but no info how that can be accessed.

On the other hand the product theme object does not have any attribute for metafields.

How can I access product metafields in a stencil template?

1 Answers

You can add the GraphQL query to fetch the metafields into the Front Matter at the top of the parent page template, for example product.html

And then from there, you can access it like any other handlebars property (under the gql top-level key) - so you may need to pass the result into your component for example.

Here's what that might look like in product.html:

---
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 productMetafieldsById($productId: Int!) {
  site {
    product(entityId: $productId) {
      metafields(namespace: \"my-namespace\") {
        edges {
          node {
            key
            value
          }
        }
      }
    }
  }
}
"

You would then access this via {{gql.data.site.product.metafields}}

An easy way to consume it would look like:

{{#each gql.data.site.product.metafields.edges}}
  {{#with node}}
    {{key}}
    {{value}}
  {{/with}}
{{/each}}

Metafields will only be available in the storefront if they have a permission_set containing storefront, otherwise they will be hidden from the storefront.

You can also invoke the GraphQL API directly from the Stencil frontend if you prefer, and you can test your queries using the "Storefront API Playground" under Advanced Settings in the control panel.

Related