I’m in need of some help! 🙂
What I’m trying to do is let a user create a post from the front end. With a preview window of how the post will look like when published. This I have already accomplished. Now I’m trying to allow the user to upload a image directly into the media library. This upload needs to happen as soon as the user has chosen the file with the follow code:
<form method="post" action="#" enctype="multipart/form-data" >
<input type="file" name="featured_image">
</form>
I don’t want any page load, is there a way to get the file without using a submit button?
Also how do I handle the actual file upload, my google skills found this function:
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;
}
But this function hooks the upload to a post, I just want it to go straight into the library without being connected to a post. Also I assume the $file_handler is the name of the form? I also assume that $_FILES doesn’t exists unless the user has clicked a submit button.
I’m prolly way off here, talking out of my ass. So any help would be appriciated. Any WP-gurus available? 😀
I had the same problem. The WordPress Documentation helps:
http://codex.wordpress.org/Function_Reference/wp_handle_upload
http://codex.wordpress.org/Function_Reference/wp_insert_attachment
UPDATE: $key is the name of the type=”file”
I just added the guid value, because it doesn’t seem to be added (and maybe there are better ways, then including admin.php:
Ok, I’m getting forward. I’m now using this jquery plugin for image uploading ->
http://lagoscript.org/jquery/upload
Which is very lightweight and works great. Uploads the image to my computer without refreshing. It saves the file in a temp dir on my server, what I’m planning to do now is somehow inject this image into the media library (and then delete it from the temp folder), but this seems harder than it should.
Is there any way I can add a image to the media library with php-code, using only a image url?
I can’t seem to find one, but since WP has this feature in the admin-area already there must be a way.
The easiest way seems to be just creating a custom field that stores the image for that post, but I really want to be able to use WPs thumbnail functions, not only for looping, but for resizing etc.
Any pointers?
I am using this code working is fine
javascript
HTML
<