Use variables in input queries
You can use variables in the GraphQL input query of your function. This allows a function to have merchant configured values used as the variables for your input query. For example, you can use these variables to check if a product is
hasAnyTag to add custom logic to your function.
The values for the input query variables can be set using metafields when creating a function owner. Variables allow you to customize the data requested by your input query, which is used as input to your function.
This guide shows you how to use variables in input queries with Shopify Functions.
RequirementsAnchor link to section titled "Requirements"
- You're using Shopify CLI version
- You're familiar with metafields concepts and APIs.
Step 1: Specify the metafield to useAnchor link to section titled "Step 1: Specify the metafield to use"
To specify which metafield contains the input query variables, you need to set the values in the
extensions.input.variables section of the function's settings:
If you're using a previous version of the configuration file that doesn't have an
[[extensions]] section, then the configuration section for input query variables is called
Step 2: Set the metafieldAnchor link to section titled "Step 2: Set the metafield"
Functions can use a metafield on the function owner to populate the variables for their GraphQL input query. The definition of variables and their values is similar to the use of variables when invoking GraphQL over HTTP. Input query variables value are managed by your app using a
JSON metafield type.
Your app can allow merchants to customize the variable's values that are needed for your input query. If you want to check if any product is
inAnyCollection, then you can set a
JSON metafield to store values for the variable named
selectedCollectionIds. The values for the keys of this metafield must be set to the correct type for that field.
For example, setting a
selectedCollectionIds variable of type
[ID!] would require a metafield value such as the following:
This variable value can be set using the metafield collection on the create or update mutation on your function owner (for example,
Step 3: Use the Anchor link to section titled "Step 3: Use the metafield as input query variables"
metafield as input query variables
If input query variables are specified in your function's settings file, then they must be used in your input query. When Shopify runs your function, the
JSON value of the specified metafield is used as variables to the input query. The keys in the
JSON object must correspond to the variable names.
The following example shows how to use the values provided by the merchant for a
selectedCollectionIds variable in an input query. Using the query results, you could check if a product is in any of the collections specified and then apply the discount accordingly: