I wrote a plugin that creates a custom post type with custom fields. To prevent users from entering incorrect information, how can I validate the data?
I assumed that the save_post hook function would process field validation, but I can’t seem to find a straight forward way that displays errors back to the user.
Is there a built-in wordpress function/feature for this? What is the general technique for accomplishing custom field validation?
You’re on the right track. I test the fields in the
save_post
callback, and then use admin notices to display errors to the user when a field fails validation. They show up just in a highlighted box at the top of the page, just like any errors/messages that WordPress itself generates.Here’s a simple example of creating an admin notice:
That’s not very practical, though. In a situation like this, you really just want a function that you can pass a message to. Something like,
So, you can write that
enqueue()
function yourself (along with a function to print the notices), or you can include a library like IDAdminNotices.Here’s an example from a plugin I wrote. This uses notice enqueue/print functions that are built into the class itself, rather than including an external library.
I wrote a small plugin that not only validates the input fields on custom post types but also removes the default admin notice, without the use of Javascript.
here is some of the code
/ Validation filters
You can see the full tutorial here
When
save_post
runs, it has already saved the post on the database.If you are using ACF, it has built-in validation.
However, if you need to validate things outside of ACF, such as post_title, things get a little more complicated.
Looking into WordPress core code, more specifically at the
wp-includes/post.php
‘supdate_post()
function, there is no built-in way to intercept a request before it is saved on the database.However, we can hook
pre_post_update
and useheader()
andget_post_edit_link()
to prevent the post from being saved.I just want to add to the excellent answer of @Lucas Bustamante that the value of custom fields can be accessed via
$_POST
global.Thus, @Lucas Bustamante answer is also valid if the validation refers to a custom field. For example:
you can use “wp_insert_post_data” filter to modifier or check data before it is inserted into the database