Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save LaChouetteInformatique/9aab395f076b1a0ae0309f27872c797c to your computer and use it in GitHub Desktop.
Save LaChouetteInformatique/9aab395f076b1a0ae0309f27872c797c to your computer and use it in GitHub Desktop.
Simple script to validate post data before saving it.
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