How to use category metafields in your theme

Once you have created your category metafield, and you have enabled storefront access, it can be queried using GraphQL.

One way to do this would be simply design your query and then make a JavaScript request. The downside of this is that any changes then become "client-side". 

We recommend testing out new graphQL queries in the storefront API playground first.

However, there's a better way. A powerful part of stencil themes is the ability to add GraphQL queries to the front matter. When you do this, BigCommerce makes the response to this request available server-side. This means you can use GraphQL data within your template. 

For example, this query will search for a metafield with key "space_48" and key "test_content" within the current category. By adding it to the theme front matter a new object will be available for access in the template, e.g. gql.

---
category:
    shop_by_price: true
    products:
        limit: {{theme_settings.categorypage_products_per_page}}
gql: "query categoryById($categoryId: Int!) {
    site {
        category(entityId: $categoryId) {
            metafields(namespace:\"space_48\",keys: [\"test_content\"]) {
                edges {
                    node {
                        value
                    }
                }
            }
        }
      }
    }
"
---

Assuming that this was raw HTML then it could be outputted at the top of the page by adding this to the category.phtml template and using triple braces `{{{ }}}`:

<div class="page-content" id="product-listing-container">
    {{#each gql.data.site.category.metafields.edges}}
        {{{node.value}}}
    {{/each}}

    {{> components/category/product-listing}}
    {{{region name="category_below_content"}}}
</div><br>

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

{{#each gql.data.site.category.metafields.edges}}
    {{#eq node.value "Yes"}}
       The flag was enabled for this category.
    {{/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.category.metafields.edges}}
    {{#and (if node.key '==' "test_flag") (if node.value '==' "Yes") }}
        The flag was enabled for this category.
    {{/and}}

    {{#if node.key '===' "test_content"}}
        {{{node.value}}}
    {{/if}}
{{/each}}<br>
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us