Metabox saves on Update or Publish, but not on Saving Draft

I have created custom post types that also have custom meta_boxes I’ve created. Currently, they save when I publish or update a post, but they don’t save when I’m in draft mode making changes.

add_action('save_post', 'save_details');

function save_details(){
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
    return $post_id;
}
global $post;
if ($post->post_type == 'events') { // Check to see if Event Type.
    update_post_meta($post->ID, "event_featuring", $_POST["event_featuring"]);
    update_post_meta($post->ID, "event_time", $_POST["event_time"]);
    update_post_meta($post->ID, "event_date", $_POST["event_date"]);
    update_post_meta($post->ID, "event_end_date", $_POST["event_end_date"]);
    update_post_meta($post->ID, "event_location", $_POST["event_location"]);
    update_post_meta($post->ID, "empid", $_POST["empid"]);
    update_post_meta($post->ID, "bhs_event", $_POST["bhs_event"]);
}
}

I tried using wp_insert_post_data instead of save_post, but then I had the opposite problem. It would save on Drafts, but publishing the post no longer worked. What do I need to do differently so I can update a draft (before publishing) and it will save?

Related posts

Leave a Reply

2 comments

  1. So you first tried hooking on to wp_insert_post_data and could save the meta data when saving Drafts but not when publishing. Then you tried hooking on to save_post and could save meta data when publishing but not when saving Drafts.

    The easiest solution would be to hook on to both.

    add_action('save_post', 'save_details');
    add_action('wp_insert_post_data', 'save_details');
    

    Edit

    Both save_post and wp_insert_post_data are called at the same time and pass two parameters to callback functions. In the source, it looks like this:

    do_action('save_post', $post_ID, $post);
    do_action('wp_insert_post', $post_ID, $post);
    

    Bbut your function isn’t accepting any parameters. This will make return $post_ID fail and will likely cause other issues as well.

    You should have:

    function save_details( $post_ID, $post ) {
        ...
    }
    

    And your hook should be:

    add_action( 'save_post', 'save_details', 10, 2 );
    

    This will pass both $post_ID and $post into your function and should make things run a bit more smoothly.

  2. I was having a similar problem which I think was triggered by upgrading wordpress to 3.1 although I did not get a chance to revert back to verify. I changed my code to pass in the $post_id and $post as above taking care to pass parameter 1,2 rather than 10, 2 as above and this fixed the problem. adding a hook to wp_insert_post did not work for me and gave me errors when adding a new custom post.

    Hope this help. My first response so sorry if I’m unclear.