Custom field values get deleted

Check your variables before you work with them. Your save function gets a parameter $post_id. Use it.

From my meta box class for a check box:

/**
 * Saves the content to the post meta.
 *
 * @return void
 */
public function save( $post_id )
{
    $this->is_allowed_save( $post_id ) and
        update_post_meta( $post_id, $this->vars['key'],
            empty ( $_POST[ $this->vars['key'] ] ) ? 'off' : 'on' );
}

/**
 * Checks if we should trigger the save action.
 *
 * @param  int  $post_id
 * @return bool
 */
protected function is_allowed_save( $post_id )
{
    // Check integrity, proper action and permission
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
    {
        return FALSE;
    }
    if ( ! wp_verify_nonce( $this->nonce, $this->vars['title'] ) )
    {
        return FALSE;
    }
    if (    ! current_user_can( 'edit_post', $post_id )
        and ! current_user_can( 'edit_page', $post_id )
    )
    {
        return FALSE;
    }

    return TRUE;
}

As you can see, DOING_AUTOSAVE is something you want to avoid. Authorization is the next point, otherwise anybody can post anything to your blog. And prepare the data before you insert them into the DB.

Leave a Comment