We're moving the community! Starting July 7, the current community will be read-only for approx. 2 weeks. You can browse content, but posting will be temporarily unavailable. Learn more

Issue in get Collection-Wise Products with category metafield Filters with Storefront GraphQL API

Issue in get Collection-Wise Products with category metafield Filters with Storefront GraphQL API

rahul-ghaskata
Shopify Partner
1 0 1

Hi Shopify Community,

I’m trying to fetch products from a specific collection using filter type category metafield via the Storefront API in Laravel but I am facing some issues.

My objective is to filter products based on category metafield values such as age group, fabric, etc. However, I am facing the following issues:

Issue:

  • The API is not returning products filtered by the category metafield. Instead, it either returns all products or products filtered by other criteria but not the specified category metafield filters.

On the storefront side, those filters are working well.
Here are the filters highlighted - https://prnt.sc/CtCpZOUng65j

Here are my filters:

 

{
  "filters": [
    {
      "id": "filter.v.t.shopify.age-group",
      "label": "Age group",
      "type": "LIST",
      "values": [
        {
          "id": "filter.v.t.shopify.age-group.gid-shopify-taxonomyvalue-XXXXXXXXXXXXXX",
          "label": "0-6 months",
          "input": {
            "categoryMetafield": {
              "namespace": "shopify",
              "key": "age-group",
              "value": "gid://shopify/TaxonomyValue/XXXXXXXXXXXXXX"
            }
          },
          "count": 3
        },
        {
          "id": "filter.v.t.shopify.age-group.gid-shopify-taxonomyvalue-XXXXXXXXXXXXXX",
          "label": "7-12 months",
          "input": {
            "categoryMetafield": {
              "namespace": "shopify",
              "key": "age-group",
              "value": "gid://shopify/TaxonomyValue/XXXXXXXXXXXXXX"
            }
          },
          "count": 3
        }
      ]
    }
    // Other filters here...
  ]
}

 

 

Here is the code I used to call the API.

 

class ShopifyGraphQLService
{
  /**
   * Send a CURL request to the Shopify API
   */
  public function handleCurlRequest(string $url, string $query, array $headers = [], string $method = 'POST', array $customOptions = [])
  {
      $res = ['isSuccess' => false, 'message' => 'Something went wrong!!!', 'data' => []];
      try {
          $curl = curl_init();
          curl_setopt_array($curl, [
              CURLOPT_URL => $url,
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_CUSTOMREQUEST => $method,
              CURLOPT_HTTPHEADER => array_merge(['Content-Type: application/json'], $headers),
              CURLOPT_POSTFIELDS => $query,
          ] + $customOptions);
          $response = curl_exec($curl);
          $curlError = curl_error($curl);
          curl_close($curl);
          if ($curlError) {
            $res['message'] = 'Curl error: ' . $curlError;
          } else {
            $response = json_decode($response, true);
            $res['isSuccess'] = !isset($response['errors']);
            $res['message'] = $res['isSuccess'] ? 'Request successful' : 'API error: ' . json_encode($response['errors']);
            $res['data'] = $res['isSuccess'] ? ($response['data'] ?? []) : [];
          }
      } catch (\Throwable $th) {
        $res['message'] = $th->getMessage();
      }
      return $res;
  }

  /**
   * Fetch products from a collection using category metafield filters
   */
  public function fetchProductsWithFilters()
  {
    // GraphQL query to fetch products with metafield filters
    $graphqlQuery = <<<GQL
    query @inContext(country: IN, language: EN) {
      collection(id: "MY__COLLECTION__ID") {
        products(
          first: 20
          sortKey: TITLE
          reverse: false
          filters: [
            {
              productMetafield: {
                namespace: "shopify"
                key: "age-group"
                value: "gid://shopify/TaxonomyValue/XXXXXXXXXXXXXXX"
              }
            },
            {
              productMetafield: {
                namespace: "shopify"
                key: "age-group"
                value: "gid://shopify/TaxonomyValue/XXXXXXXXXXXXXXX"
              }
            }
          ]
        ) {
          edges {
            cursor
            node {
              id title vendor totalInventory productType tags handle
              options { values }
              variants(first: 1) {
                edges {
                  node {
                    id title
                    priceV2 { amount currencyCode }
                    compareAtPriceV2 { amount currencyCode }
                  }
                }
              }
              images(first: 1) {
                edges {
                  node {
                    url
                  }
                }
              }
            }
          }
          pageInfo {
            hasNextPage hasPreviousPage startCursor endCursor
          }
        }
      }
    }
    GQL;
    $url = 'https://your-shopify-store.myshopify.com/api/2024-10/graphql.json';
    $headers = [
      'X-Shopify-Storefront-Access-Token: YOUR-ACCESS-TOKEN-XXXXXXXXXXXXXXXX-HERE',
      'Accept: application/json',
    ];
    $response = $this->handleCurlRequest($url, json_encode(['query' => $graphqlQuery]), $headers);
    return $response;
  }
}

 

 

 

My Questions:

I’d like to understand if there are any issues or required changes with the following:

  1. Query Structure:

    • Am I missing any required parameters or structuring the query incorrectly?
  2. Parameters in Query:

    • Are the values passed to the query (e.g., namespace, key, value) accurate, or do they need adjustments?
  3. Store Settings:

    • Do I need to enable or disable any specific settings in the Shopify store for metafield-based filtering to work properly?
  4. Other Considerations:

    • Is there anything else I should be aware of to make meta field-based filtering function as expected?

Request:

I would be grateful for any suggestions, solutions, or references (e.g., documentation, examples) that could help me resolve this issue.

Thank you in advance for your assistance!

Replies 0 (0)