How Can I pass an image file to wp_handle_upload?

I have been looking everywhere for this and havent been able to find an answer.

I need to pass a file from the url source to wp_handle_upload. How can I accomplish this?

Read More

Thank you

Related posts

Leave a Reply

2 comments

  1. As @Rarst said, most convenient way to handle an external upload and create the related attachment post is use media_sideload_image(), this function:

    • Download the url
    • Verify if it is a valid a image and if so
    • create the attachment post
    • attach this attachment to a specific post whose id is passed as argument
    • return the img html tag for the image

    However, sometimes one may want just access to attachment post id and is not interested in attache the attachment to any post, in this case WordPress has no built-in function, so the most convenient way is copy part of core from media_sideload_image() and part of media_handle_sideload():

     function custom_media_sideload_image( $image_url = '', $post_id = false  ) {
       require_once ABSPATH . 'wp-admin/includes/file.php';
       $tmp = download_url( $image_url );
       // Set variables for storage
       // fix file filename for query strings
       preg_match( '/[^?]+.(jpe?g|jpe|gif|png)b/i', $image_url, $matches );
       $file_array['name'] = basename($matches[0]);
       $file_array['tmp_name'] = $tmp;
       // If error storing temporarily, unlink
       if ( is_wp_error( $tmp ) ) {
        @unlink($file_array['tmp_name']);
        $file_array['tmp_name'] = '';
       }
       $time = current_time( 'mysql' );
       $file = wp_handle_sideload( $file_array, array('test_form'=>false), $time );
       if ( isset($file['error']) ) {
        return new WP_Error( 'upload_error', $file['error'] );
       }
       $url = $file['url'];
       $type = $file['type'];
       $file = $file['file'];
       $title = preg_replace('/.[^.]+$/', '', basename($file) );
       $parent = (int) absint( $post_id ) > 0 ? absint($post_id) : 0;
       $attachment = array(
         'post_mime_type' => $type,
         'guid' => $url,
         'post_parent' => $parent,
         'post_title' => $title,
         'post_content' => '',
       );
       $id = wp_insert_attachment($attachment, $file, $parent);
       if ( !is_wp_error($id) ) {
        require_once ABSPATH . 'wp-admin/includes/image.php'; 
        $data = wp_generate_attachment_metadata( $id, $file );
        wp_update_attachment_metadata( $id, $data );
      }  
      return $id;
    }
    

    This function act as media_sideload_image() but return the attachment id, or a WP_Error if something goes wrong.

    It takes an optional argument $post_id to attach media to a specific post/page, but if not passed, the attachemnt post is created but not attached to any post.