Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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"] );
}
share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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.

share|improve this answer
    
you bet me to it but that's the location i was aiming with my comments, nice +1 –  Bainternet May 16 '11 at 14:21
    
Thank you! I am confused about the save function though.. can you please explain how is works? –  MF1 May 16 '11 at 16:32
    
Also, the website that I am building isn't a blog, it's a CMS which only the website owner will make changes to after logging in. –  MF1 May 16 '11 at 16:39
    
@MF1 I linked to my Meta Box Class. This is just an example code; usually I implement two levels of abstraction more. But it should tell you how it works. –  toscho May 16 '11 at 16:42
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.