Added protecting hooks

This commit is contained in:
2026-09-25 12:42:38 +02:00
parent 9a18434f4a
commit b82ef82f50
33 changed files with 733 additions and 6 deletions
+20
View File
@@ -0,0 +1,20 @@
import type { CollectionBeforeChangeHook } from 'payload'
/**
* Sets `publishedAt` to now the first time a document transitions to published,
* if it isn't already set. Saves editors from filling the date manually and
* keeps blog/article dates accurate for Article JSON-LD and sitemaps.
*
* Attach to collections with drafts enabled (blog, articles):
* hooks: { beforeChange: [setPublishedAtHook] }
*
* Only sets on the published transition; never overwrites an existing date
* (an editor can still backdate manually).
*/
export const setPublishedAtHook: CollectionBeforeChangeHook = ({ data, originalDoc }) => {
const becomingPublished = data._status === 'published' && originalDoc?._status !== 'published'
if (becomingPublished && !data.publishedAt) {
data.publishedAt = new Date().toISOString()
}
return data
}