I was recently working on a WordPress project that required a specialized front-end panel for users to add new posts, including images and videos. Adding a post wasn’t a challenge, but handling file uploads was looking like a pain… at least trying to follow the codex documentation. After browsing the wp-includes core files for a few hours, though, I found a much easier way of handling it.

According to the codex entry for wp_insert_attachment, adding an attachment to a post should be achieved by a function like the following:

  $wp_filetype = wp_check_filetype(basename($filename), null );
  $attachment = array(
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
     'post_content' => '',
     'post_status' => 'inherit'
  $attach_id = wp_insert_attachment( $attachment, $filename, 37 );
  // you must first include the image.php file
  // for the function wp_generate_attachment_metadata() to work
  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
  wp_update_attachment_metadata( $attach_id,  $attach_data );

I spent several hours struggling to make this function work. The wp_insert_attachment() function is simple enough—it will take an uploaded file, given a server path, and add it as an entry to the wp_posts table with type “attachment”. So if you’ve already processed the user upload, sanitized the title, checked the mime-type, and saved it to your uploads directory, this step is simple enough. The functions in lines 12 and 13, wp_generate_attachment_metadata() and wp_update_attachment_metadata(), set the attachment’s mime-type and associate it with the proper post parent.

But there’s something glaring missing here. In order to use an uploaded image with any of WordPress’s built-in image functions, you really need to generate thumbails and all the intermediate and custom image sizes that work with get_the_post_thumbnail, get_attachment_image, and all the other attachment-related image functions. And for most sites, trusting users to upload images at a specific size isn’t really an option. I’m not about to have my entire layout broken because someone uploaded a 6 megapixel jpg as the thumbnail for their post.

So how does WordPress go about creating these intermediate sizes? I looked around the wp-admin files to see how its done within the admin panel. I came across a couple really handy functions in wp-admin/includes/media.php. The one which worked for me was media_handle_upload(). This function does everything from sanitizing and ensuring unique name for the file, resizing the uploaded file to all the intermediate sizes, and generating and updating the attachment metadata.

So, long story short, my function for handling user-uploaded images was reduced from a 40-line monstrosity to this simple, easy, and secure 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;

Very satisfying. While I was looking for this code, I saw a lot of questions in support forums from other people trying to get similar functionality. So I’m posting this in case it helps anyone. Happy coding!

85 Responses

  1. Comment from gabe

    Any chance you could supply a bit more info about how to implement this into production?

    • Reply to gabe, from Than

      Sure. It depends a bit on what you’re trying to do with the uploads. I needed to give my client dashboard access to change the form structure, so I ended up using a contact form plugin (Dagon Design Formmailer) and hacking the response handler in it. A simpler method would just be using a page template for the page with the form on it, like this.

      Assuming you have a form on the page something like this:

      <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">

      just include the function insert_attachment() above somewhere in the page template (or in your functions.php if you want to use it more than one place). Then include a handler something like this, near the top of your page template:

      // 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.

      (Note: I fixed this example code after Josh and iROKM pointed out errors in it below —thanks.)

      Hope this helps!

  2. Comment from saul

    Hi!, sorry for my english..but I need your help!!

    I try to put a upload form in a page template, but I don’t know what target write in the action="" argument of the form.

    If I put action="http://www.site.com/?page_id=45" (this is itself, the form page), it doesn’t work with an input type="file". The worpress response is:”Not Found
    Apologies, but the page you requested could not be found.”, but the url is correct..

    What I do wrong?? thanks!

    • Reply to saul, from Than

      Did you make sure you’re using POST as the form action? This might be a bit obvious, but… using GET as the form action will probably screw up your WordPress rewrite rules: you’ll end up with an unreadable URL like http://site.com/?page_id=45?yourformfield=value that WP will trip over in parsing the query.

      In addition, the <input type="file"> form element only works when the form’s method="POST" and enctype="multipart/form-data".

      Let me know if that helps…

      • Reply to Than, from saul

        I forgot this…

        “In addition, the form element only works when the form’s method=”POST” and enctype=”multipart/form-data”.”


  3. Comment from saul

    hey! You know hoy I can changue de value of “post_title” of an attachment??

    I try with:

    $data = array('post_title' => 'my title',);	

    but not works…

    • Reply to saul, from Than


      I haven’t had to go this route, but it looks like the argument you need to pass to wp_update_attachment_metadata() is generated by the call to wp_generate_attachment_metadata(). You could fit it into one line like this:

      wp_update_attachment_metadata( $attach_id, wp_generate_attachment_metadata( $attach_id, $filename ) );

      Edit: Actually, I was curious and went and looked at the source of wp_generate_attachment_metadata. The attachment metadata doesn’t have anything to do with the post title of the attachment – that’s set when you insert the attachment or upload the media, and if you need to update the title, I would guess the best way to do that would be wp_update_post() — attachments are stored in the wp-posts table same way as other post types.

  4. Comment from Josh

    Thanks for the info. I’m getting an odd error on the file upload:

    Warning: Illegal offset type in /home/vetlive/domains/vetlive.com/public_html/dev/wp-admin/includes/media.php on line 194

    Warning: Illegal offset type in /home/vetlive/domains/vetlive.com/public_html/dev/wp-admin/includes/media.php on line 195

    It looks like it’s not getting the array that it expects in the $_FILES. I tried calling it specifically from the field name (avatar_upload in this instance $_FILES["avatar_upload"]) Did you run into this in your implementation at all?


    • Reply to Josh, from Than

      No, I didn’t see that issue, but your guess seems like its right on. I would try a test, like var_dump($_FILES['avatar_upload']), to make sure the file is there when your code is processed. You may need to attach your code to a later action hook, and test for the existence of the file before trying to handle the upload…

    • Reply to Josh, from iROKM

      Josh, I got this error as well when using his example.

      Give this a shot on a single upload

      $newupload = insert_attachment('an_uploaded_attachment',$post_id);

      That worked for me.

      • Reply to iROKM, from Than

        @Josh and iROKM –

        You’re right, I should have double-checked my code example before posting it. In my site I was calling the function from the name of the field, and I didn’t check the structure of the $_FILES array – just assumed it would work. If you replace the first line of that loop with

        foreach ($_FILES as $file =>$array), NOT foreach ($_FILES as $file),

        it should work. I’ll edit the example above so it doesn’t confuse anyone else.

  5. Comment from Chris

    Hi Than! First of all thank you very much for posting this script.

    I have a request for you which I think many others would greatly appreciate as well.

    I am looking to add a new metabox to the post edit screen and create my own file upload box but I want to ensure that any uploaded file is using the default wordpress media library.

    The problem I am having is that I don’t know how to go about modifying your script so that I can create metaboxes in the admin screen.

    Would you please provide an example here of exactly what we would need to add to the functions.php file so a new upload metabox can be added to a post edit screen?

    • Reply to Chris, from Than

      Hi Chris,

      Thanks for dropping by…

      I’m just getting back to normal after moving last week and an awesome time at WordCamp PDX this past weekend. I’ll write up the code to do that in another post in just a bit. It’ll take a bit of playing with some of the callbacks in admin-ajax, which I’m not so familiar with. But I do need to do something very similar for a project of my own, so this is as good a time as any to learn…

  6. Comment from JJ Peters

    i tried the code, but it doesn’t upload any image. I put the insert_attachment() function in functions.php and the

    if ($_FILES) {
      foreach ($_FILES as $file => $array) {
        $newupload = insert_attachment($file,$post_id);

    just after the if ($_POST['submit']) { of my form.

    My input is like:

    Can you please help me out?

    • Reply to JJ Peters, from Than

      I’d check your form structure and see what’s being posted from it. if ( $_POST['submit'] ) will probably always return false, so if your file upload code is within that conditional, it will probably never be called.

      Also check the enctype of your form. Unless enctype="multipart/form-data" is set, the $_FILES array will not be populated and your upload file fields will just show up as filenames in the $_POST array.

  7. Comment from JJ Peters

    here is my form code:

    Post Title:

    <input type="text" name="title" value="" />

    And this is the Submit code:

    if ($_POST['submit']) {
    global $user_ID, $wpdb;
    $new_post = array(
    				'post_title' => wp_filter_nohtml_kses($_POST['title']),
    				'post_content' => $_POST['post'],
    				'post_status' => $post_status,
    				'post_date' => date('Y-m-d H:i:s'),
    				'post_author' => $user_ID,
    				'post_type' => 'post',
    				'post_category' => $_POST['cats'],
    				'tags_input' => implode(',',$tags)
    if (!$error) {
    global $demo;
    if (!$demo) {
    $post_id = wp_insert_post($new_post);
    			} else {
    				$error = $error;

    This form works right, the post title is being posted right in database. Where i’d put your code?
    Thanks for patient and for share this code…

    • Reply to JJ Peters, from Than

      No problem.

      I’d still need to see the file upload fields from your form, and the initial definition of the form. IF the form is setup with the following attributes:

      <form method="post" enctype="multipart/form-data">

      and you have one or more <input type="file"> fields in your form, then uploaded files will be in the $_FILES array. In that case, adding the code you posted above right after the line which inserts the post ( $post_id = wp_insert_post($new_post);) should work.

      Unrelated: I’m starting to realize how difficult it is to post code snippets in these comments. For the most part, including snippets within <code> or <pre> tags should do it, but sometimes even that doesn’t protect the text. Try replacing <> signs with &lt; and &gt; for now. I’ll look for a comments plugin that handles code better.

  8. Comment from JJ Peters

    i’ve figured out!! thank you!! it was my error, i put the enctype in the input file instead in the form attributes…

  9. Comment from franck

    I can not display images in single.php and category.php
    ID, 'Thumbnail', $ single = true);?>
    does not work, like many other.
    more downloaded files are identified in the table ‘wp_postmeta’ and associate it with a post_id (=> wp_post) different from the editing section since my form.
    is this normal?
    thank you for your patient and understanding my bad English

  10. Comment from Erich

    Hello. I’m using your script and the image uploads and everything, but when I go to post the image, it only displays the attachment ID, not the actual URL? Have any idea how to fix this?

    Here’s my code:

    foreach ($_FILES as $file => $array) {
    	    $fontpair = wp_insert_attachment($filename);
    	    // $newupload returns the attachment id of the file that
    	    // was just uploaded. Do whatever you want with that now.
    	// Add the content of the form to $post as an array
    	$post = array(
    		'post_title'	=> $title,
    		'post_content'	=> '<img src="'.$fontpair.'" />',
    		'post_category'	=> $cat_Arr, // Usable for custom taxonomies too
    		'post_image'	=> $newupload,
    		'post_status'	=> 'publish'	 // Choose: publish, preview, future, etc.
    	wp_redirect( home_url() );
    } // end IF
    // Do the wp_insert_post action to insert it
    do_action('wp_insert_post', 'wp_insert_post'); 
    • Reply to Erich, from Than

      (I cleaned up the code you posted as best I could… hopefully this is what you were trying to post.)

      I’m not sure exactly about the context of your code, but the problem you’re having is trying to get the src of an image from its attachment id. Both the WP API wp_insert_attachment() and the customized variant on it that I posted above insert_attachment() return an attachment ID number, not an image resource or the source of an image file.

      You can get the src of your attachment like this:

      $image = wp_get_attachment_image_src( $fontpair );
      $post['post_content'] = '<img src="'.$image[0].'" width="'.$image[1].'" height="'.$image[2].'" />';

      Look at the codex entry for wp_get_attachment_image_src.

  11. Comment from Erich

    Cool, thanks. I ended up getting the url by:

    $newupload = wp_get_attachment_url(insert_attachment($file,$_POST['post_id']));

    I imagine your way is cleaner, so I’ll use it instead.

    I’m still having a couple issues… I’m not able to attach the upload to the post using $upload_id = insert_attachment($file,$_POST['post_id']); I guess I don’t know how to get the $post_id of the post being created?

    Using jQuery, I’ll make sure the same category isn’t selected twice, but I’d like to set the post category to the two selected categories, so: 'post_category' => [the value of the first dropdown (style1)] and [the value of the second dropdown style2)]

    <code> </code> is how to properly denote code in the comments here, right?

    I’m sorry for all my questions. I’m a front-end designer trying to do some more back-end stuff I’m not accustomed to. I guess it’s good for me, though frustrating.

  12. Thanks a lot for very nice script, i did a very best job here on
    i have successfully inserted post title, content and also image from front end. you can see the script in action here.
    If anyone need any support plz mail me or visit my website at http://www.vaseemansari.com/blog/

    • Reply to Vaseem Ansari, from Joanna

      Can you share some info on how you compile this?
      i have build a post form (frontend) and i need to add image upload also but i don’t have the knowledge!

      if you can help a bit more it would be nice!


  13. Comment from sony

    I written the detail and simple code to upload file through add_meta_box function. check the following article.

    • Reply to sony, from Than

      Very nice. I was over-thinking this problem and making it a lot more complicated than it needs to be. Thats a sweet and simple way of handling admin meta-box uploads.

      I tried to leave a comment over at your site, but your comment form isn’t working. So here it is. My only critique… why not store the attachment ID in the “product_image” field, rather than the absolute url?

      That way, you could make use of more of the built-in attachment functions.

  14. Comment from Andy

    Exactly what I needed. Thank you very much for posting.

  15. Comment from John

    I wanted to use Uploadify to make a neat user file upload system – this post helped me out so thank you!

  16. Comment from Will

    Thanks for posting such helpful info.

    I was wondering is there a way to include a caption or alt text relating to the specific image you upload?

    • Reply to Will, from Than

      Yeah, title, caption, and description are all stored in the attachment post in a very similar way to any other post type.

      Title is stored in post_title.
      Caption is stored in post_excerpt.
      Description is stored in post_content.

      So, after you’ve uploaded an image with the id $attach_id, just call wp_update_post like this:

      wp_update_post( array(
        'ID' => $attach_id,
        'post_title' => "New image title",
        'post_excerpt' => "New image caption",
        'post_content' => "New image description" )
      • Reply to Than, from aaron

        That you for that snippet of code! That is what i was looking for.

  17. Comment from Will

    Thanks Than for getting back to me, really appreciate it. Your code works perfectly but I am trying to store the caption for multiple input fields with no success. Here is my input form, it works but only one image and caption are uploaded:

    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.
    for($i=0;$i $value) {
      wp_update_post( array(
      'ID' => $newupload,
      //'post_title' => "New image title",
      //'post_content' => "New image description"
      'post_excerpt' => $_POST['caption'][$i]
    • Reply to Will, from Than

      I’d have to see your input form to see how your data is coming in. I don’t know why you have two separate loops, though. Why not just set your caption right after uploading the file, in the same loop?

  18. Comment from Saxon

    Thank you for this function!

    Just thought I would contribute. If you uploading multiple files but the input field names are in array form (e.g. ) which WordPress can handle, then you could also use :

    	 * Fixes the odd indexing of multiple file uploads from the format:
    	 * $_FILES['field']['key']['index']
    	 * To the more standard and appropriate:
    	 * $_FILES['field']['index']['key']
    	 * @param array $files
    	 * @author Corey Ballou
    	 * @link http://www.jqueryin.com
    	function fix_file_array(&$files) {
    		$names = array(
    			'name' => 1,
    			'type' => 1,
    			'tmp_name' => 1,
    			'error' => 1,
    			'size' => 1
    		foreach ($files as $key => $part) {
    			// only deal with valid keys and multiple files
    			$key = (string) $key;
    			if (isset($names[$key]) && is_array($part)) {
    				foreach ($part as $position => $value) {
    					$files[$position][$key] = $value;
    				// remove old key reference
    	foreach ($_FILES[$name] as $file => $fileitem){
    		$newupload = insert_attachment($fileitem,$real_post_id);
    function insert_attachment($file_handler,$post_id,$setthumb='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_sideload( $file_handler, $post_id );
    		if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
    		return $attach_id;

    Hope that helps!

  19. Comment from Daniel

    great post, thanks for sharing

  20. Comment from Joanna

    hi, thanks for this information,
    is it possible for someone here have make this code work to share a complete solution?
    a form with the needed code to upload an image or images?

    i try to understand where to put this code in a page template with a form that already handle a post form…


  21. Comment from Joanna

    thanks a lot, it’s working excellent, just seen that it uploads the files in the library,
    is it possible to include the images in the post_content while submitting the post?

    thanks a lot!

    • Reply to Joanna, from Than

      Great, glad its working!

      It shouldn’t be a problem to include the images in your post content, but you’d have to decide where you want them to appear, what size you want to import them as, etc…

      Here’s a simple modification that adds the “large” size uploaded image to the end of the post content: do something like this after uploading the file:

      $old_post = get_post( $post_id );
      $attachment = get_attachment_image( $attach_id, 'large' );
      wp_update_post( array(
          'ID' => $post_id,
          'post_content' => $old_post->post_content . $attachment
      • Reply to Than, from Dmitry

        get_attachment_image() didn’t work for me but wp_get_attachment_image() did.

        Thank you for this post, it saved me a lot of time.

  22. Comment from Joanna

    thanks a lot Than, you are a genius,

    i have found a way to attach the images uploaded in a post and it’s working fine except that:

    i have 4 upload fields in my form (like in your example),
    if a user uploads 4 images the 4th image attached as a “Featured Image” and shows it correct in the admin area Post Columns and in the Post Edit “Featured Image” window,
    if the user selects to upload 1 or 2 or 3 images, in the admin area Post Columns it shows an error:

    Catchable fatal error: Object of class WP_Error could not be converted to string in /Applications/MAMP/htdocs/wordpress303/wp-includes/post.php on line 3687

    i’m missing something? did you understand where is my problem?

    thanks a lot for your help and sharing your knowledge with us,

    • Reply to Joanna, from Than

      That error is coming from not checking to see if an image was successfully uploaded. The function I posted will return a WP_Error if an upload did not finish successfully. Try wrapping the function which adds the image to the post content in a test like this:

      if ( isset( $attach_id ) && !is_wp_error( $attach_id ) ) {
      // ... the function above, or whatever you do with the images
  23. Comment from Joanna

    sorry, i’m not make it clear,
    i’m not use the function in your last comment (#comment-1770),
    i have send you a message,

    thanks a lot for your help!!!

  24. Comment from Joanna

    thank you very much Than,

    i found the problem,
    i have put my function between your code and now everything is working fine,

    thank you very much!!!!

  25. [...] Golden Apples Design proponen un método alternativo utilizando la función media_handle_upload(), sobre la que hay muy poca información. A mí no me ha [...]

  26. Comment from Enrico

    Hi everyone!

    Thanks for the script, I got it working. Though I have a question/problem. I have been using this for making posts on wp. My problem is I have the “file input form” on page1 which also gets some user datas, then goes to page2 which gets some more user datas, then all will be processed at page3 making and publishing the entire post. The codes work when it is process on the next form, but if I skipped form and process everything there the image is not uploaded. I’ve been on this all day and its driving me nuts already. Can this code that what I need?

    • Reply to Enrico, from Than

      That’s a tricky implementation, since the data in the $_FILES array isn’t going to be carried over from one form to the next. You’ll have to handle the image upload after the first page of the form using this function or something similar. Upload the image without attaching it to a post (i.e., call the upload function with 0 as your $post_id). Return the image attachment ID, and populate a hidden field with that ID. Finally, when you get to the last step and insert / publish your post, go back and edit the attachment, setting its post id to the id of the post.

      • Reply to Than, from Enrico

        Thanks Than,
        I ended up putting the form on the second page, my client did say so. It gave me the creeps on thinking of doing as I’ve spent a day googling for answers. Thank you very much for the reply as your site is very helpful.

        Many Thanks!

  27. Thank you so much!! I was building a custom script to do this, then found your post while searching on information regarding the _thumbnail_id. Kablamo! Works like a charm.

    Because I’m working inside a custom ajax php class, I also needed to add the wp-load.php:

    require_once ($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php')

    …and call the function correctly within the class:

    $newupload = $this->insert_attachment($file,$post_id);

    Thanks again.

  28. Comment from martin

    this is working great except I need one more thing.
    I have a submit post page and edit post page. On edit page if there is no file chosen it removes the attachment when the post is updated. Can someone share a solution, Im sure it can be handled.

    • Reply to martin, from Than

      Sounds like a logic problem in your edit post page… you probably should be checking whether an upload is present before trying to handle it. Try

      if ( isset( $_FILES['yourformfieldname'] ) && 
           ($_FILES['yourformfieldname']['error'] == UPLOAD_ERR_OK ) ) {
           ## handle attachment upload here...

      to make sure that a file is selected before trying to do anything with it.

  29. Comment from Per

    Yup, what he said ^

    Besides that it works splendidly!

  30. You are a total life saver! This worked perfectly and it was easy to follow. After many hours of frustrations trying to get several different options to work, this was the one that worked on the first try.

  31. Comment from Binh Nguyen

    Hey, many thanks about the tip, it save my time :)

  32. Comment from Diana

    Quite a question on frontend forms… would you ever write how to add metadata fields? I only have to match the field IDs with the ones I created?!

    • Reply to Diana, from Than

      You mean metadata fields for the attachment itself? It should be pretty straightforward. After you’ve handled the image upload, you should get the attachment ID for that image. Then you can just call update_post() or update_post_meta() with the meta fields that you want to add. Caption, title, mime type, and description are stored in the post itself; if you want to add non-standard meta, you can just use the postmeta table.

  33. Comment from Pauly

    Hi! thanks for the tip! one question, i have a page where I created a post, with custom fields, it’s a way to upload image, video, and other files in this custom fields?For example, I have a custom fields (textarea) where the users upload particular information, I want to add a button, then the user click that button, and media upload windows open, select file and insert into this textarea?
    Sorry for my english!

  34. Comment from Ethan

    Thanks for the great post Than! I’ve seen this snippet all over the WP StackExchange.

  35. [...] http://goldenapplesdesign.com/2010/07/03/front-end-file-uploads-in-wordpress/ This entry was posted in How To, WordPress Design. Bookmark the permalink. ← Creating an Animated GIF [...]

  36. Comment from ZigPress

    You, sir, are a gentleman and a scholar. That is an incredibly cool and useful piece of code.

  37. Comment from patrick91

    Hi, thanks for this useful script, I’m using it in the admin but when I try to upload a BIG file I get no POST and no FILES and even no errors :(

    Can you help me?

    • Reply to patrick91, from Than

      When you say “BIG” files, how big are you talking about? You’re not going to be able to exceed the size of your upload_max_filesize or post_max_size (usual default = 8MB, although many shared hosts set that number lower) through this method. You’ll need to set up some kind of chunking method to get around that limit.

      Since you’re handling uploads in the WP admin section, though, why reinvent the wheel? The WP media uploader is pretty good at handling large uploads, and its fairly easy to repurpose for your own methods. There are a few decent tutorials out there explaining how to do that; here’s the first one I’m finding right now. Basically it just involves a little bit of javascript to monkeypatch the window.send_to_editor method on the media upload thickbox, and then you do what you want with the upload.

      Only caveat is that the media upload code is going through a lot of changes in core. If you’re going to try something like this for public release, I would pay close attention to the latest changes being discussed on trac

  38. Have you any idea if we could set the destination folder of the file that the user upload???

    • Reply to Andres, from Than

      You can filter the directory that the upload goes into by adding a filter on upload_dir. But keep in mind that attachment locations are stored relative to the uploads directory. So if you try and save your upload outside of the uploads directory, your path will have a lot of ../../ ugliness. (Not to mention that other directories aren’t guaranteed to be writable in most WP environments.)

  39. Comment from Ed

    Thanks so much mate, excellent help, very clever. Got it working on my site in around 10 mins after trying other methods for hours. thanks!

  40. Comment from Derrick


    is it possible to change the filename of the uploaded media ?


  41. Comment from screamwork

    Hi, thx for sharing. I really appreciate posts like that…

  42. Comment from Rob

    I’m going a little nuts.

    I can use the code to create an attachment and get a valid attachment id. But for some reason I can get the thumbnail to update with the standard code:

    update_post_meta($post_id, ‘_thumbnail_id’, $attachment_id);

    I have a valid post_id. The post inserts fine. The attachment_id is valid. I can actually access the attachment with other WP functions. But when I look at the post in the admin panel, the thumbnail (featured image) is empty. I get no error.

    Any thoughts?

  43. Comment from Rob

    Problem solved!

    Thanks for the code.

  44. Comment from Chris Baker

    function attach_image_url($file, $post_id, $desc = null) {
    require_once(ABSPATH . “wp-admin” . ‘/includes/image.php’);
    require_once(ABSPATH . “wp-admin” . ‘/includes/file.php’);
    require_once(ABSPATH . “wp-admin” . ‘/includes/media.php’);
    if ( ! empty($file) ) {
    // Download file to temp location
    $tmp = download_url( $file );
    // Set variables for storage
    // fix file filename for query strings
    preg_match(‘/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/’, $file, $matches);
    $file_array['name'] = basename($matches[0]);
    $file_array['tmp_name'] = $tmp;
    // If error storing temporarily, unlink
    if ( is_wp_error( $tmp ) ) {
    $file_array['tmp_name'] = ”;
    // do the validation and storage stuff
    $id = media_handle_sideload( $file_array, $post_id, $desc );
    // If error storing permanently, unlink
    if ( is_wp_error($id) ) {@unlink($file_array['tmp_name']);}
    add_post_meta($post_id, ‘_thumbnail_id’, $id, true);

  45. Comment from Mantish

    Thanks for this post!
    You just saved me a lot of work

  46. [...] to be attached to a particular post. I am able to get it to work with single images thanks to this post at Golden Apples [...]

  47. Hi Than.

    Great, thanks. Needed this for a client project, decided to look up some things about the way WordPress handles file uploading. Copied your snippets, changed a few things and voila. You just saved me a few hours of looking into the core. :-)

    All the best, Danny.

  48. Comment from Ryan

    You are my hero. This solution works perfectly, and saved me hours. I also managed to get captions working great with your assistance in the comments. Thank you!

  49. Comment from Monika

    I have done post from front end using “post from site” plugin added custom fields ,image as a featured image .
    Now i want to upload video from front end this should be attached with post .
    can you help me plzz to accomplish this task.


  50. Comment from Kenth Hagström

    Totally awesome, scratched my head on this subject for a few hours before finding your post! Many thanks!

Leave a Reply