Can you use multiple fields as sources when generating a slug in Sanity?

2 replies
Last updated: Apr 24, 2020
Is it possible to provide more than one field as a source when generating a slug? Something like
source: "title && date"
AI Update

Yes, absolutely! You can use multiple fields as a source when generating a slug. Instead of passing a simple string to the source option, you can use a function that receives the document and returns a combined string.

Here's how to do it:

{
  name: 'slug',
  type: 'slug',
  options: {
    source: (doc) => `${doc.title} ${doc.date}`,
    maxLength: 96
  }
}

The source option accepts a function that receives the entire document as an argument, allowing you to access and combine any fields you need. The function should return a string that will be slugified when you click the "Generate" button in the Studio.

You can get creative with this - for example, you might want to combine a category with a title:

source: (doc) => `${doc.category} ${doc.title}`

Or format a date along with the title:

source: (doc) => {
  const date = new Date(doc.publishedAt).toISOString().split('T')[0];
  return `${date} ${doc.title}`;
}

The function gives you full flexibility to construct the source string however you need before it gets converted into a URL-friendly slug. Just remember that the actual slugification (converting to lowercase, replacing spaces with hyphens, etc.) happens automatically after your function returns the combined string.

You can do a function for `source`:
source: doc => `${doc.title} ${doc.date}`
The value you return from that should be the actual value that gets slugified – not the name of the field as a string.

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?