Last active
November 13, 2024 20:57
-
-
Save valentin-grenier/7bb13997c1f9207feba623e654649f52 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
/* | |
* 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