Custom field values get deleted
-
22-10-2019 - |
Question
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"] );
}
Solution
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange