2

Setup:

  • WordPress Add/Edit Post/Page
  • A plugin that have its own postbox with several hidden fields.

Issue:

How these custom hidden fields can be saved along with the other post data within the Autosave feature?

Thanks

2

I have just made a plugin that needed to be autosaved, so i started to dig into the code. I did now that it have to be trigged by some javascript so started to look into the console in Chrome when autosave fires. I then saw that autosave.js looks for a class tags-input in admin-filters.php you can see the comment:

// NOTE: the class "tags-input" allows to include the field in the autosave $_POST (see autosave.js)

So i just added the class tags-input to my hidden fields and it now saves when autosave fires!

Here is my example: <input type="hidden" class="tags-input" name="key" value="value" />

Update:

Now you have to add your data by your own ajax function. (add a new js-file and include in footer. admin_enqueue_scripts)

jQuery(document).ajaxSend(function(e, x, a) {
    var data = 1;
    a.data += '&' + jQuery.param( {test_data: data} );
});

And the saving:

add_action('save_post', 'autosave_save_custom');

function autosave_save_custom( $post ) {
    if( wp_is_post_autosave($post) && isset( $_POST['test_data'] ) ) {
        $test_data = intval( $_POST['test_data'] );
        $post_id = $post->ID;
        update_metadata( $post->post_type, $post_id, 'test_data', $test_data );
    }
}
  • Neat, but that its safe to do? I mean, when you restores the autosave its doesn't get those values and to set the tags? – diosney Aug 23 '13 at 21:31
  • I searched and didn't found any mention to tags-input there so I think can be used :D However, had you any issues regarding this? – diosney Aug 23 '13 at 21:34
  • There are other plugins that using this method, such as Polylang. And no your values will not get the tags. I think the ajax-request looks for the class tags-input to build the data posted to the database. – Pontus Abrahamsson Aug 23 '13 at 21:37
  • He..What version of WP are you using? I checked a WP 3.5.2 installation and it have the code you say except the comment :( which is bad indication. In a WP 3.6 installation It has the code...**commented!** :O with a message that reads: /* // We haven't been saving tags with autosave since 2.8... Start again? $('.the-tags').each( function() { data[this.name] = this.value; }); */ – diosney Aug 23 '13 at 21:38
  • Anyway, was a good suggestion but do you have another way? This one seems inconsistent and unsafe since WP team removed that feature. – diosney Aug 23 '13 at 21:39

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.