I have a custom post type (CPT) called event
. I have a meta box for the type with several fields. I would like to validate some fields before publishing an event. For example, if an event’s date is not specified I would like to display an informative error message, save the event for future editing, but prevent that event from being published. Is ‘pending’ status for an CPT post without all necessary info the right way to treat it?
What’s the best practice to do CPT fields validation and prevent a post from being published, but save it for future editing.
Many thanks,
Dasha
You can stop the post from saving all together with minor JQuery hacks and validate the fields before saving on the client side or server side with ajax:
first we add our JavaScript to capture the submit/publish event and use it to submit our own ajax function before the actual submit:
then we create the function to do the actual validation:
you can always change it up a bit to do the validation only for your post type by adding a conditional check to
my_publish_admin_hook
function for your post type and to validate on the client side but i prefer on the server side.There are two steps to the 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…
I haven’t tested this exact code, but it’s a simplified version of what I’ve done in large-scale custom post type setups.
For multiple metabox fields, just add more completion markers and retrieve more post_meta and do more tests..
you have to check/validate your meta field value on ajax i.e. when user hit “Publish/Update” button.
Here i am validating woocommerce product having meta field “product_number” for empty value.
After that add ajax handler function,
Just wanted to add that to read the post variables, using Bainternet’s solution, you’ll have to parse the string in
$_POST['form_data']
using PHPparse_str
function (just to save you some research time).Then you can access each variable just using
$varname
. For example, if you have a meta field called “my_meta” you would access it like this: