Forked from valentin-grenier/block-editor-validation.js
Created
November 7, 2024 08:05
-
-
Save LaChouetteInformatique/9aab395f076b1a0ae0309f27872c797c to your computer and use it in GitHub Desktop.
Simple script to validate post data before saving it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let isNoticeDisplayed = false; | |
wp.data.subscribe(() => { | |
const hasCategory = wp.data.select('core/editor').getEditedPostAttribute('categories'); | |
const postType = wp.data.select('core/editor').getCurrentPostType(); | |
// == Check if there are no categories selected | |
if (postType === 'post' && (!hasCategory || hasCategory.length === 0)) { | |
if (!isNoticeDisplayed) { | |
// Lock post saving and show a notice if not displayed already | |
isNoticeDisplayed = true; | |
wp.data.dispatch('core/editor').lockPostSaving('require-category'); | |
wp.data.dispatch('core/notices').createNotice('warning', 'You must select a category to save your question.', { | |
id: 'require-category', | |
isDismissible: false, | |
}); | |
} | |
} else if (isNoticeDisplayed) { | |
// == If a category is selected but the notice is still displayed | |
isNoticeDisplayed = false; | |
wp.data.dispatch('core/editor').unlockPostSaving('require-category'); | |
wp.data.dispatch('core/notices').removeNotice('require-category'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment