0

Create Smart Collection

by
Published Nov 8, 2023

Create a collection whose products are picked automatically by conditions.

Script shopify Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 2 hours ago
1
//native
2

3
/**
4
 * Create Smart Collection
5
 * Create a collection whose products are picked automatically by conditions. Each condition is one object keyed by its type, e.g. {"productTag": {"relation": "TAGGED_WITH", "values": ["sale"], "matchType": "ANY"}}, {"productVendor": {"relation": "EQUALS", "values": ["Acme"], "matchType": "ANY"}}, {"variantPrice": {"relation": "LESS_THAN", "value": {"amount": "20", "currencyCode": "USD"}}}. Types: productTag, productTitle, productType, productVendor, productStatus, productCategory, variantTitle, variantPrice, variantCompareAtPrice, variantInventory, variantWeight, metafield*. The collection is created unpublished.
6
 */
7
export async function main(
8
  auth: RT.Shopify,
9
  title: string,
10
  conditions: { [key: string]: any }[],
11
  match_type: "ALL" | "ANY" | undefined,
12
  description_html: string | undefined,
13
  handle: string | undefined,
14
  sort_order:
15
    | "BEST_SELLING"
16
    | "ALPHA_ASC"
17
    | "ALPHA_DESC"
18
    | "PRICE_ASC"
19
    | "PRICE_DESC"
20
    | "CREATED"
21
    | "CREATED_DESC"
22
    | "MANUAL"
23
    | undefined
24
) {
25
  const response = await fetch(
26
    `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`,
27
    {
28
      method: "POST",
29
      headers: {
30
        "X-Shopify-Access-Token": auth.token,
31
        "Content-Type": "application/json",
32
        Accept: "application/json",
33
      },
34
      body: JSON.stringify({
35
        query: `mutation ($collection: CollectionCreateInput!) { collectionCreate(collection: $collection) { collection { id legacyResourceId title handle descriptionHtml sortOrder productsCount { count } sources { id title ... on CollectionConditionsSource { inclusion { matchType conditions { __typename id } } } } } userErrors { field message } } }`,
36
        variables: {
37
          collection: {
38
            title,
39
            descriptionHtml: description_html || undefined,
40
            handle: handle || undefined,
41
            sortOrder: sort_order || undefined,
42
            sources: [
43
              {
44
                source: {
45
                  title,
46
                  inclusion: { matchType: match_type || "ALL", conditions },
47
                },
48
              },
49
            ],
50
          },
51
        },
52
      }),
53
    }
54
  )
55

56
  if (!response.ok) {
57
    throw new Error(`${response.status} ${await response.text()}`)
58
  }
59

60
  const { data, errors } = await response.json()
61
  if (errors) {
62
    throw new Error(JSON.stringify(errors))
63
  }
64
  if (data.collectionCreate.userErrors.length) {
65
    throw new Error(JSON.stringify(data.collectionCreate.userErrors))
66
  }
67

68
  return data.collectionCreate
69
}
70

Other submissions
  • Submitted by hugo697 Typescript (fetch-only)
    Created 528 days ago
    1
    type Shopify = {
    2
      token: string;
    3
      store_name: string;
    4
    };
    5
    /**
    6
     * Creates a smart collection
    7
     * Creates a new smart collection using the specified rules.
    8
     */
    9
    export async function main(
    10
      auth: Shopify,
    11
      api_version: string = "2023-10",
    12
      body: {
    13
        smart_collection?: {
    14
          published?: boolean;
    15
          rules?: {
    16
            column?: string;
    17
            condition?: string;
    18
            relation?: string;
    19
            [k: string]: unknown;
    20
          }[];
    21
          title?: string;
    22
          [k: string]: unknown;
    23
        };
    24
        [k: string]: unknown;
    25
      }
    26
    ) {
    27
      const url = new URL(
    28
        `https://${auth.store_name}.myshopify.com/admin/api/${api_version}/smart_collections.json`
    29
      );
    30
    
    
    31
      const response = await fetch(url, {
    32
        method: "POST",
    33
        headers: {
    34
          "Content-Type": "application/json",
    35
          "X-Shopify-Access-Token": auth.token,
    36
        },
    37
        body: JSON.stringify(body),
    38
      });
    39
      if (!response.ok) {
    40
        const text = await response.text();
    41
        throw new Error(`${response.status} ${text}`);
    42
      }
    43
      return await response.json();
    44
    }
    45