I have a custom post type with several custom fields. I am looking to do some validation on these fields because they will be used downstream by other services. So, it is important that it can’t be saved until it is correctly entered. The validation is reasonably complex and requires custom logic.
Unfortunately, it also won’t work to use a plugin in this particular case.
Is there an ideal hook to use in this case? At a high level — whats the best way to go about this.
Example code in
add_meta_box()
documentation usessave_post
hook (at the very end ofwp_insert_post()
function) to add custom fields data from metabox.You must be using something like that already in your metaboxes, is it not appropriate place to validate your data?..
(Taken from my answer to a similar question posted here)
There are two steps to this method: first, a function to save your custom metabox field data (hooked to save_post), and second, a function to read that new post_meta (which you just saved), validate it, and modify the result of saving as necessary (also hooked to save_post, but after the first). The validator function, if validation fails, actually changes the post_status right back to “pending”, effectively preventing the post from being published.
Since the save_post function gets called a lot, each function has checks to only execute when the user means to publish, and only for your custom post type (mycustomtype).
I also typically add some custom notice messages to help the user know why their post didn’t publish, but those got a bit complicated to include here…
For multiple metabox fields, just add more completion markers and retrieve more post_meta and do more tests..