0

Create Custom Collection

by
Published Nov 8, 2023

Create a manual collection, optionally with initial products.

Script shopify Verified

The script

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

3
/**
4
 * Create Custom Collection
5
 * Create a manual collection, optionally with an initial list of products (numeric IDs or GIDs). The collection is created unpublished; publish it to a sales channel to show it to customers.
6
 */
7
export async function main(
8
  auth: RT.Shopify,
9
  title: string,
10
  product_ids: string[] | undefined,
11
  description_html: string | undefined,
12
  handle: string | undefined,
13
  image_url: string | undefined,
14
  sort_order:
15
    | "MANUAL"
16
    | "BEST_SELLING"
17
    | "ALPHA_ASC"
18
    | "ALPHA_DESC"
19
    | "PRICE_ASC"
20
    | "PRICE_DESC"
21
    | "CREATED"
22
    | "CREATED_DESC"
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 } } userErrors { field message } } }`,
36
        variables: {
37
          collection: {
38
            title,
39
            descriptionHtml: description_html || undefined,
40
            handle: handle || undefined,
41
            image: image_url ? { src: image_url } : undefined,
42
            sortOrder: sort_order || undefined,
43
            sources: product_ids?.length
44
              ? [
45
                  {
46
                    source: {
47
                      title,
48
                      inclusion: {
49
                        selections: product_ids.map((id) => ({
50
                          productId: id.startsWith("gid://")
51
                            ? id
52
                            : `gid://shopify/Product/${id}`,
53
                        })),
54
                      },
55
                    },
56
                  },
57
                ]
58
              : undefined,
59
          },
60
        },
61
      }),
62
    }
63
  )
64

65
  if (!response.ok) {
66
    throw new Error(`${response.status} ${await response.text()}`)
67
  }
68

69
  const { data, errors } = await response.json()
70
  if (errors) {
71
    throw new Error(JSON.stringify(errors))
72
  }
73
  if (data.collectionCreate.userErrors.length) {
74
    throw new Error(JSON.stringify(data.collectionCreate.userErrors))
75
  }
76

77
  return data.collectionCreate
78
}
79

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 custom collection
    7
     * Creates a custom collection
    8
     */
    9
    export async function main(
    10
      auth: Shopify,
    11
      api_version: string = "2023-10",
    12
      body: {
    13
        custom_collection?: {
    14
          image?: { alt?: string; src?: string; [k: string]: unknown };
    15
          title?: string;
    16
          [k: string]: unknown;
    17
        };
    18
        [k: string]: unknown;
    19
      }
    20
    ) {
    21
      const url = new URL(
    22
        `https://${auth.store_name}.myshopify.com/admin/api/${api_version}/custom_collections.json`
    23
      );
    24
    
    
    25
      const response = await fetch(url, {
    26
        method: "POST",
    27
        headers: {
    28
          "Content-Type": "application/json",
    29
          "X-Shopify-Access-Token": auth.token,
    30
        },
    31
        body: JSON.stringify(body),
    32
      });
    33
      if (!response.ok) {
    34
        const text = await response.text();
    35
        throw new Error(`${response.status} ${text}`);
    36
      }
    37
      return await response.json();
    38
    }
    39