0

I recently read this tutorial about custom fields in WordPress and wrote a simple plug-in to provide a metabox with a set of input fields.

I do not use the Meta Box plug-in promoted on the web site.

My implementation for the save_post hook is as follows:

function save_my_data( $post_id ) {
  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
    return;
  }
  if ( get_post_status( $post_id ) === 'auto-draft' ) {
    return;
  }
  if ( $parent_id = wp_is_post_revision( $post_id ) ) {
    $post_id = $parent_id;
  }

  $fields = array( 'foo', 'bar' );

  foreach ( $fields as $field ) {
    if ( array_key_exists( $field, $_POST ) ) {
      update_post_meta( $post_id, $field, sanitize_text_field( $_POST[ $field ] ) );
    }
  }
}
add_action( 'save_post', 'save_my_data' );

The tutorial mentions two aspects that I'm stuck with, because they simply redirect to their own plug-in solutions:

  1. Auto-save: WordPress auto-saves a post every 60 seconds while editing, as I learned in the tutorial. The draft is kept in a temporary database entry and deleted within 7 days. Custom fields, however, are not auto-saved.

How can I auto-save my custom fields as well and make sure that they are cleaned-up properly, if I abandon a draft?

  1. Revisions: Later on, the tutorial mentions that every now and then a revision of a blog post is created. Here again, custom fields are not stored in the revisions. And again, they refer to one of their commercial plug-ins.

How can I make sure, my metadata is stored in the revisions, too?

Basically, what I'm asking for is whether there is a best practice and WordPress offers any tools to store data in drafts/revisions or whether all plug-in developer have to come up with their own solutions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.