Custom Data disappears on Custom Post Types

With WordPress 3.0 Custom Post Types came to life and within the project I am working on we started to use them, each post needs to have a set of custom data to associate with. Basically we were adding new posts with custom data and everything was looking fine in the front end, but after a while the custom data would disappear from the blog entry without any post update being performed on the backend… strange strange voodoo. Some checks on the logs and on the database showed no errors so something else was triggering this behavior, there was no voodoo at all this was due to the “autosave” routine performed when you have the “Edit Post” page on the dashboard open.

The problem is that the autosave option does not pass by post the Custom Fields we add to the Custom Post type so when the “save post data” is called those fields are set to blank and you loose your data. Its extremely easy to avoid this by adding an extra hidden field which will work as an id for your custom data form.


echo '<input type="hidden" name="myplugin_noncename" id="myplugin_noncename" value="' .wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

This id will then be used when you save the post data to check if the request came from the “edit post” screen and with proper authorization since this could be triggered at other times.

You can use this code for that purpose:

if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}

Another possible solution is to simple check if the save post data was triggered by the autosave routine and if so discard that request since it will not include your custom data.

Here is the code for that which should be also added before the save data is performed,

if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;

more details here!

…and that’s more than enough on this subject 🙂

Advertisements

One thought on “Custom Data disappears on Custom Post Types

  1. Anon says:

    How about instead of using functions to declare what is essential nothing more then a constant, a known value you use this:

    3 being some random number or string, it can be anything. The point is, knowing what the value will be.
    then in the save function:
    if($_POST[‘constantCheck’] == 3){

    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: