Skip to main content

How to use product and variant metafields in your theme

After you create a product or product variant metafield and enable storefront access, you can query it with GraphQL.

You can send the query from JavaScript, but changes made this way are client-side.

info

We recommend testing new GraphQL queries in the Storefront API playground first.

However, Stencil themes can run GraphQL queries in front matter. BigCommerce makes the response available server-side, so you can use the GraphQL data in your template.

For example, this query searches the custom namespace for the test_content key on the current product and its variants. Adding it to the theme front matter makes the response available as gql in the template.

---
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) {
entityId
name
metafields(
namespace: \"custom\"
keys: [\"test_content\"]
) {
edges {
node {
key
value
}
}
}
variants {
edges {
node {
metafields(
namespace: \"custom\"
keys: [\"test_content\"]
) {
edges {
node {
key
value
}
}
}
}
}
}
}
}
}
"
---

If the metafield contains raw HTML, render it in the product template with triple braces ({{{ }}}):

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

Alternatively, if the metafield was used to enable/disable functionality per product. It could be checked within a condition like so:

{{#each gql.data.site.product.metafields.edges}}
{{#eq node.value "Yes"}}
The flag was enabled for this product.
{{/eq}}
{{/each}}

If you have more than one metafield key selected in your query, you can perform a check based on key name:

{{#each gql.data.site.product.metafields.edges}}
{{#if node.key '===' "test_flag" and node.value '===' "Yes"}}
The flag was enabled for this product.
{{/if}}
{{#if node.key '===' "test_content"}}
{{{node.value}}}
{{/if}}
{{/each}}