prevent post submission

See the Codex, on save_post. In answer to Question 1, it is fired whenever WordPress auto_saves a revision (i.e. hence when a post is edited). In particular, when creating a new post, wp-admin/post-new.php is loaded. WordPress then creates an auto draft even if you haven’t saved a draft or published to post. This is intended as it means stuff like the media uploads functions properly.

You shouldn’t try to prevent it from running, but instead, check in your hooked function that it is not an auto-save routine:

add_action('save_post','my_save_function');
function my_save_function($post_id) {

    //You should have a nonce to check the data came from your metabox

    // verify this is not an auto save routine. 
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;

    //Or: if (wp_is_post_revision( $post_id ) ) return;

    //perform authentication checks
    if (!current_user_can('edit_post', $post_id)) return;

    $raw_data = $_POST['name_of_input_field'];
    //Sanitise your data
    }

In answer to Q2: returning false in the above function doesn’t prevent the post saving. This is because WordPress just fires the action ‘save_post’ but does not consider any returns from it, and proceeds to save the post (EDIT: In fact, save_post is called after the post is inserted into the database).

You could ‘exit’ the process, like this answer, but if you want to check the metabox has been filled in, I suggest using jQuery instead. If you wish to display an error notice if your metabox wasn’t correctly filled in, see this post.

I’m not sure why you are asking Q3 – WordPress handles the sanitisation of stuff like the title before it saves it to the database – you don’t have to worry about that. Or are you wanting to use the title in a custom field?

In short though, so long as you use something like update_post_meta to save data to the database, you don’t need to escape the data. But with regards to which checks you should perform prior to that depends on what you are willing to except as the data input. On output you should be escaping data – but quite how again depends on context. See this post.

Leave a Comment