Add validation and error handling when saving custom fields?

I have a function that defines a custom field on a post type. Say the field is “subhead”.

When the post is saved, I want to do some validation on the input, and display an error message on the post edit screen if necessary. Something like:

// Handle post updating
function wpse_update_post_custom_values($post_id, $post) {

    // Do some checking...
    if($_POST['subhead'] != 'value i expect') {

        // Add an error here
        $errors->add('oops', 'There was an error.');

    }

    return $errors;

} 
add_action('save_post','wpse_update_post_custom_values',1,2);

I’m trying to hook this to the save_post action, but I can’t figure out how to handle errors. There doesn’t appear to be an error object passed into the function, and if i create my own WP_Error obj and return it, it’s not respected by whatever mechanism spits out errors on the post edit page.

I currently have an on-page error message inside my custom meta box, but this is less than ideal–I’d rather have a big, red, up-at-the-top error like WP normally displays.

Any ideas?

UPDATE:

Based on @Denis’ answer, I tried a few different things. Storing errors as a global didn’t work, because WordPress does a redirect during the save_post process, which kills the global before you can display it.

I ended up storing them in a meta field. The problem with this is that you need to clear them out, or they won’t go away when you navigate to another page, so I had to add another function attached to the admin_footer that just clears out the errors.

I wouldn’t have expected that error handling for something so common (updating posts) would be this clunky. Am I missing something obvious or is this the best approach?

// Handle post updating
function wpse_5102_update_post_custom_values($post_id, $post) {

    // To keep the errors in
    $errors = false;

    // Do some validation...
    if($_POST['subhead'] != 'value i expect') {

        // Add an error here
        $errors .= 'whoops...there was an error.';

    }

    update_option('my_admin_errors', $errors);

    return;

} 
add_action('save_post','wpse_5102_update_post_custom_values',1,2);


// Display any errors
function wpse_5102_admin_notice_handler() {

    $errors = get_option('my_admin_errors');

    if($errors) {

        echo '<div class="error"><p>' . $errors . '</p></div>';

    }   

}
add_action( 'admin_notices', 'wpse_5102_admin_notice_handler' );


// Clear any errors
function wpse_5102__clear_errors() {

    update_option('my_admin_errors', false);

}
add_action( 'admin_footer', 'wpse_5102_clear_errors' );

7

Store errors in your class or as a global, possibly in a transient or meta, and display them in admin notices on POST requests. WP does not feature any flash message handler.

Leave a Comment