I'm facing an annoying issue that I can't solve.
I've made this code in order to add or update an attachment on a custom post type :
function add_update_attachment( $postID, $photo ) {
if ($photo == '') return;
$basename = basename($photo);
$basenameExp = explode("?", $basename);
$name = $basenameExp[0];
$attach = array_shift(get_attached_media('image', $postID));
$attachName = basename( $attach->guid );
$wp_upload_dir = wp_upload_dir();
$fileName = $wp_upload_dir['path']. "/".urldecode($name);
$fileType = wp_check_filetype( $name, null );
// echo '<pre>'.print_r($wp_upload_dir, true).'</pre>';
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . $name ,
'post_mime_type' => $fileType['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', $name ),
'post_content' => '',
'post_status' => 'inherit'
);
if ( str_replace('%20', ' ', $attachName) !== $photo ) {
wp_update_post( array( 'ID' => $attach->ID, 'post_parent' => 0) );
copy ( $photo, $wp_upload_dir['path']. "/" . urldecode($name) );
$attachID = wp_insert_attachment( $attachment, $fileName, $postID );
$attachData = wp_generate_attachment_metadata( $attachID, $fileName );
wp_update_attachment_metadata( $attachID, $attachData );
set_post_thumbnail( $postID, $attachID );
}
}
The problem is that : some of my post are dupplicating for no reason.
I have this post (I'm showing a custom field only) :
Array
(
[0] => LieuTemp001
[1] => LieuTemp002
)
And the last one is dupplicated. Why ? I have no problem if I don't use this function (but I need to use it, obsviously)