Golden Apples Design created (as far as I know) the media upload function that many people on WP.A and elsewhere seem to recommend. But all of the Q&As I can find on StackExchange deal with creating an entirely new post.
What is the best way to get this (or another snippet) to upload media from the front-end, attach it to the current post, generate the appropriate thumbnails, and then refresh the page showing the new image in the ?
Here is Than’s code:
In functions file…
function insert_attachment($file_handler,$post_id,$setthumb='false') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
In page template header…
// set $post_id to the id of the post you want to attach
// these uploads to (or 'null' to just handle the uploads
// without attaching to a post)
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post_id);
// $newupload returns the attachment id of the file that
// was just uploaded. Do whatever you want with that now.
}
}
Upload form used…
<form method="post" action="#" enctype="multipart/form-data" >
<input type="file" name="an_uploaded_attachment">
<input type="file" name="another_uploaded_attachment">
<input type="file" name="yet_another_uploaded_attachment">
<input type="submit">
<form>
@AboSami actually answered this question in an older post that was not showing up in my search diligence. While he was actually looking for something else his example code worked great.
Here’s the script:
In your header change
$post_id
to$post->ID
.