✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Adding multiple categories to a product in Sanity.io

11 replies
Last updated: Jun 15, 2023
Hello devs, How I can assign two categories to the same product? like a shirt could be in Featured Category as well as Shirt category
Jun 14, 2023, 10:07 PM
Hi! 👋 If
category
is an array of categories, you can add more than one.
Jun 14, 2023, 10:09 PM
import { defineType } from "sanity";


export const category = defineType({

name: "category",

title: "Category",

type: "array",

fields: [

{

name: "name",

title: "Category Name",

type: "string",

},


],

});
Jun 14, 2023, 10:17 PM
getting this error on fields:Argument of type '{ name: "category"; title: string; type: "array"; fields: { name: string; title: string; type: string; }[]; }' is not assignable to parameter of type '{ type: "array"; name: "category"; } & Omit<ArrayDefinition, "preview">'.
Jun 14, 2023, 10:18 PM
Also, I'm referencing this into my product file
Jun 14, 2023, 10:19 PM
Like this
export const products = {

name: "products",

title: "Products",

type: "document",

fields: [

{

name: "title",

title: "Product Title",

type: "string",

},

defineField({

name: "category",

title: "Product Category",

type: "reference",

to: [

{

type: "category",

},

],

}),

],

};
Jun 14, 2023, 10:22 PM
Sorry if I'm disturbing with this huge code coz I'm new to this:)
Jun 14, 2023, 10:22 PM
References can only be to documents, but it looks like your reference in
products
is to an array type. One way I might do this is to make
category
a document type containing a string (
title
is a convention), and then add an array of references (to
category
) in your
products
schema.
Jun 14, 2023, 10:51 PM
All I want is to add an option so that I can attach 2 categories to the same product. Stucked since yesterday😟
Jun 15, 2023, 8:22 AM
From those two recent screenshots,
category
looks good. Can you open
products
and replace lines 38-47 with this?

defineField({
  name: "categories",
  title: "Product Categories",
  type: "array",
  of: [
    defineArrayMember({
      name: "category",
      title: "Product Category",
      type: "reference",
      to: [{ type: "category" }],
    }),
  ],
})
Jun 15, 2023, 2:50 PM
(Note that the
defineArrayMember
wrapper function isn’t necessary, so omit it if you want. It improves support in your editor, like
defineType
).
Jun 15, 2023, 2:51 PM
Thank you very much, Amazing support you're providing at Sanity.❤️
Jun 15, 2023, 4:34 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?