How to add document _id to slug field using custom slugifier function
You're on the right track! You can absolutely use a function as the source option in a slug field, and this is the perfect way to combine multiple values including the _id. While the slug field technically takes a single source, that source can be a function that returns a string combining whatever fields you need.
Here's how to set this up to include the _id while removing the drafts. prefix:
{
name: 'slug',
type: 'slug',
options: {
source: (doc) => {
// Remove 'drafts.' prefix from _id if it exists
const cleanId = doc._id?.replace(/^drafts\./, '') || '';
// Combine with other fields as needed
return `${doc.title}-${cleanId}`;
},
maxLength: 96,
// Optional: customize the slugify function if needed
slugify: (input) => input
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w-]+/g, '')
}
}The key points here:
- Source function: The
sourceoption accepts a function that receives the current document (doc) as a parameter, giving you access to all fields including_id - Removing drafts prefix: Use
replace(/^drafts\./, '')to strip thedrafts.prefix from the beginning of the_id - Combining values: Return a string that combines whatever fields you need - title, date,
_id, etc.
If you want to slice just the first 7 characters after removing the prefix, you could do:
source: (doc) => {
const cleanId = doc._id?.replace(/^drafts\./, '').slice(0, 7) || '';
return `${doc.title}-${cleanId}`;
}The slug field documentation covers the basics, and as mentioned in the Sanity community answers about using multiple fields as sources, this function approach is the standard way to combine multiple document values into a single slug.
One thing to keep in mind: the slug generation happens when you click the "Generate" button in Studio, so the _id needs to exist at that point (which it will for existing documents, but new documents won't have an _id until after the first save).
Show original thread6 replies
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.