I'm writing a plugin, and I was wondering how I can display an error message after the meta fields have been updated and the page is reloaded. I have to check if the ID field is unique, and if it isn't then display an error message telling the user what the problem was, instead of just not updating the value.


As mentioned by jdm2112, WordPress provides a save_post hook that fires once a post is saved. Since you need to run validation logic when posts are saved, this hook (or its dynamic counterpart) should probably be used in your solution. As for displaying an error message when validation fails, the admin_notices hook is perfect for that.

A rough solution might look like this:

function filbr_validate_id_meta_field( $post_id ) {
    // Skip post revisions
    if ( wp_is_post_revision( $post_id ) ) {

    $id = get_post_meta( $post_id, 'id', true );

    if ( ! filbr_id_unique( $id ) ) {
        add_action( 'admin_notices', 'filbr_invalid_id_error' );
        // Optionally delete invalid meta value
        delete_post_meta( $post_id, 'id' );
add_action( 'save_post', 'filbr_validate_id_meta_field' );

function filbr_id_unique( $id ) {
    // ... check uniqueness of provided ID

function filbr_invalid_id_error() {
    <div class="notice notice-error">
        <p><?php _e( 'The ID you entered is not unique', 'your-text-domain' ); ?></p>

You'll need to tweak it to make it work as desired.

Let me know if you have any questions!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.