Hi everybody,
I have a custom field "upload image" on the user profile page.
When the user upload an image, it appear on the wordpress media library and on a featured image on a custom post.
So the first upload is ok, the image update is ok but when we do the update when there is no new image it removes the old image. (sorry for my english).
I use this code
$thumbnail_id = get_post_thumbnail_id( $post_id );
if ($thumbnail_id == "") {
$attach_id = wp_insert_attachment( $attachment, WP_CONTENT_DIR . '/uploads' . $filename, $post_id);
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, WP_CONTENT_DIR . '/uploads' . $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
}
else {
$attach_id = wp_insert_attachment( $attachment, WP_CONTENT_DIR . '/uploads' . $filename, $post_id);
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, WP_CONTENT_DIR . '/uploads' . $filename );
wp_delete_attachment($thumbnail_id );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
}