Singleton Custom Field (Meta Box)
-
02-01-2021 - |
Question
How do I create a custom meta box for posts which have a boolean data type and can be true only for one post. I want it to be falsified for all other posts when it's set on one post.
- Is there a hook that runs right after a custom field is saved in the create post screen?
- Is there a way to do this with the metabox plugin?
- For example if you want to create a featured post feature, only one post can be a featured post. Is there a way to create a single featured post without using custom meta boxes?
Solution
Storing of your own meta fields is typically a custom process, more so if you are using a third party framework.
Technically it's possible, but clunky:
- Hooking into
save_post
would allow you to check if meta is added to it - If so you can immediately query for previous (if any) post that had it and unset the meta for it
However I concur with the comment you got that this does not essentially seem to fit a purpose of post meta well. There are precedents in core itself (for example front/posts page handling) to store such things as post's ID in an option.
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange