i’m probably breaking a few common sense rules here.
is there a way to utilize wordpress’ bake in attachment file handling for
an upload form within a theme
template? yes, the front end — i know.
i’m creating a memorial site and i want people to be able to leave textual photographic “comments” for a dear person our community has lost.
but these aren’t wordpress users. they’re aunts and kids and everything in between.
these people are not going to be able to figure out WP default media UI and i don’t want them having to log in and futz around. too confusing for them. if this weren’t such a specific and delicate project, i wouldn’t be trying to bend the rules so much.
i understand that i’m opening up security holes by allowing anyone to upload a file, but i think it’s somewhat necessary. all uploaded attachments will be “pending.” i have both the text and photos set a custom post type, not as comments, so that i can utilize some built in post data.
and it would be great if i could utilize worpdress built in file checking, handling, naming, size… etc. even though the file handling is on the front end.
i thought that perhaps i could use:
wp_handle_upload()
by including ‘../wp-admin/includes/file.php’
but that didn’t work. i get a fatal error when i try to include it. is it just TOTALLY against the rules to include admin includes within templates… probably.
i could just do all the file handling myself, but thought perhaps there’s a way to utilize wordpress’ functionality and that it may be safer.
or are there suggestions on another route i should be going on altogether?
unfortunately this is pretty time sensitive… the memorial service is coming up in a few days.
thank you so much
jonah
1 Answer
here is the function i use whenever i accept uploads from front end and you can use it in your template files:
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;
}
Usage:
// 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.
}
}