I have added a custom meta box for advanced information for a specific post category, to my create new post page.

Now I recognize, that if I save the post, it writes 2 entries in the db with 2 post_ids.

add_action( 'add_meta_boxes', 'my-plugin_add_custom_box' );
add_action( 'save_post', 'my-plugin_save_postdata' );

my-plugin
function my-plugin_add_custom_box() {
    add_meta_box( 
        'my-plugin_sectionid',
        __( 'my-plugin', 'my-plugin_textdomain' ),
        'my-plugin_inner_custom_box',
        'post' 
    );
}

/* When the post is saved, saves our custom data */
function my-plugin_save_postdata( $post_id ) {
  // verify if this is an auto save routine. 
  // If it is our form has not been submitted, so we dont want to do anything
  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
      return;

  // verify this came from the our screen and with proper authorization,
  // because save_post can be triggered at other times

  if ( !wp_verify_nonce( $_POST['my-plugin_noncename'], plugin_basename( __FILE__ ) ) )
      return;


  // Check permissions
  if ( 'page' == $_POST['post_type'] ) //is this the correct post_type?
  {
    if ( !current_user_can( 'edit_page', $post_id ) )
        return;
  }
  else
  {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return;
  }

  // OK, we're authenticated: we need to find and save the data

    //$mydata = $_REQUEST['sports'];
    print($post_id); //prints two post ids e.g. 831 & 832
    //print($mydata); //prints two times content of $mydata
}

Why are two records in the tables wp_posts are created? And when I update the post, a new record is created with post_name post_id-revision (843-revision). What are the advantages for creating a new post type, like sports for such kind of posts? My advanced information like $_REQUEST['sports']; are planned to be stored in a separate db with a ref to wp_posts.

Thanks in advance & BR,

mybecks

3 Answers
3

One of the two IDs might be a post revision. To prevent this behaviour, I always have this checks in my save_postdata function:

// Autosave, do nothing
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return;
// AJAX? Not used here
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) 
        return;
// Check user permissions
if ( ! current_user_can( 'edit_post', $post_id ) )
        return;
// Return if it's a post revision
if ( false !== wp_is_post_revision( $post_id ) )
        return;

As you can see, the last condition I use here checks for the post revision. Try to use this in your function, too.

Leave a Reply

Your email address will not be published. Required fields are marked *