How WordPress autosave can save plugin fields?

Setup:

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

Issue:

Read More

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

Thanks

Related posts

1 comment

  1. 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 );
        }
    }
    

Comments are closed.