Custom field values get deleted

I created a custom post type:products which also has custom fields: price & shipping. Occasionally, if I leave the edit product window open or refresh it, I lose the values inside price and shipping. Can someone please advise on this.

add_action('save_post', 'save_details'); 
function save_details()
{ 
    global $post;
    update_post_meta($post->ID, "price",        $_POST["price"]        );
    update_post_meta($post->ID, "shipping",     $_POST["shipping"]     );
    update_post_meta($post->ID, "long_title",   $_POST["long_title"]   );
    update_post_meta($post->ID, "upload_image", $_POST["upload_image"] );
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x