What code currently does:
I feed post id & previously uploaded image id, code processes it all and does its magic described below. Result: unattached old image and new attached image.
What I need it to do:
Attach that same image to post as you can do in media screen with few clicks.
Q: Does anyone know a fix? Or maybe I made a mistakes somewhere? All comments are welcomed!
//Attach images to post
$gallery_string = $_POST['my-gallery'];
if( !empty( $gallery_string ) ) {
//It's a string (e.g '1424,3435,7544,7332') - turn it into array
$gallery_array = explode(',', $gallery_string);
foreach( $gallery_array as $value ) {
//Full path of attachment
$filename = get_attached_file( $value );
//Path to the upload directory
$wp_upload_dir = wp_upload_dir();
//Type of file
$filetype = wp_check_filetype( basename( $filename ), null );
//Prepare an array of post data for the attachment
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
//Insert the attachment
$attach_id = wp_insert_attachment( $attachment, $filename, $target_post_id );
//Needed for wp_generate_attachment_metadata()
require_once( ABSPATH . 'wp-admin/includes/image.php' );
//Generate the metadata for the attachment and update the database record
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
I know that I could use the same image ID and wp_delete_attachment()
to delete it after "duplication" but still.. Why to make things more complicated if (IF) there's a way to just attach it?
I also looked into upload.php
in wp-admin folder for the action that gets triggered when you press "attach" button in media page but it seems that it can't be used in our code (if it does, it requires pretty big hassle).