Skip to content

Instantly share code, notes, and snippets.

@valentin-grenier
Last active November 13, 2024 20:57
Show Gist options
  • Save valentin-grenier/7bb13997c1f9207feba623e654649f52 to your computer and use it in GitHub Desktop.
Save valentin-grenier/7bb13997c1f9207feba623e654649f52 to your computer and use it in GitHub Desktop.
Simple script to validate post data before saving it.
/*
* Code authored by Valentin Grenier - Studio Val
* Freelance WordPress Developer from Toulouse, France
* https://studio-val.fr/
*/
let isNoticeDisplayed = false;
const POST_TYPE = 'your-post-type';
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 (POST_TYPE === postType && (!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 post.', {
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