Attach Media to Post without Autosaving First
Question
With WordPress, I'm using wp_editor to allow users to use the editor and media uploader. I'd like to avoid creating an auto-save of the post, but the problem is that attachments have no post_id to attach to until the post is saved.
I was wondering if there was a way to upload the media and then attach it to the new post after it has been saved.
Could I pass a temporary ID to the attachment to identify it when the post is saved? Or maybe grab the attachment ID after it's been uploaded?
Ideas appreciated!
Solution
After much fussing, I came to the conclusion that the post ID upfront is necessary.
I ended up doing what the WordPress Post Edit screen does. I used a little jQuery and Ajax to dynamically create an autosave once the user has typed in a post title.
Once the autosave is done, it replaces the media upload iframe href with one containing the autosave post ID.
So, there's still a chance that there will be some abandoned post drafts, but at least it requires a little commitment by typing in the post title.
OTHER TIPS
You can create the unattached media and then attach it to a post later:
function file_into_database( $filetype, $filename, $target )
{
$title = $this->clean_file_info[ 'basename' ];
$attachment = array
(
'post_mime_type' => $filetype
, 'post_title' => $title
, 'post_content' => ''
, 'post_status' => 'inherit'
, 'guid' => $target[ 'uri' ]
, 'post_author' => $this->author
);
$attach_id = wp_insert_attachment( $attachment, $target[ 'path' ] );
$attach_data = wp_generate_attachment_metadata( $attach_id, $target[ 'path' ] );
wp_update_attachment_metadata( $attach_id, $attach_data );
return $attach_id;
}
Then later attach it:
wp_update_post
(
array
(
'ID' => $attachment[ 'id' ]
, 'post_parent' => $id_new_post
)
)
I just found this in a plugin, didn't find it documented, so I don't know if there are any side effects, but I haven't run into any. Also note that if the post eventually doesn't get posted, you won't get lingering auto-saves, but you might get lingering attachments, so you might have to schedule their deletion at some point in the future and cancel that when and if the post gets saved.