Uploading a remote image without attachment or thumbnails?

Upload Remote Image

// Attempt download.
$url = "https://site.com/path-to-image.png";
$tmp = download_url($url);

// Upload failed? Bail.
if(is_wp_error($tmp)) {
    return 'No go, mofo!'
}

// Setup file details.
preg_match('/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
$file_array = array();
$file_array['name'] = basename($matches[0]);
$file_array['tmp_name'] = $tmp;

// Error encountered? Unlink temp file.
if (is_wp_error($tmp)) {
    @unlink($file_array['tmp_name']);
    $file_array['tmp_name'] = '';
}

// Handle the upload.
$post_id = 0; // Prevents file from being attached to any post.
$upload_id = wp_handle_sideload($file_array, $post_id);

// Error handling upload? Unlink temp file.
if (is_wp_error($upload_id)) {
    @unlink($file_array['tmp_name']);
    return $upload_id;
}

// Get the resulting URL.
$src = wp_get_attachment_url($upload_id);

The above snip uploads a remote image to the media library. Passing a post_id of 0 prevents it from being attached to a post; this is desired here. Additionally, the uploaded image is then available via the media manager and the image is created at the various specified thumbnail sizes. These are desired behaviors in most cases, but, not here.

Is there an internal way to upload the file to the /uploads/2019/03/ (et al) directory while:

  • preventing attachment to a post, and
  • not showing the image in the media library, and
  • creating only the uploaded file without the various thumbnails, and
  • affording the same basic security checks as wp_handle_sideload()?

I didn’t find anything… asking before I build it.

1 Like

I think you are mixing up your function names a bit - the behavior you are looking for is what wp_handle_sideload does.

There is a separate function to create the post of type attachment that makes the media show up in the library - this is wp_insert_attachment. It takes a parent post ID, but as the third parameter rather than the second parameter.

See:

1 Like

I thought so, too… then couldn’t get it working as expected and ended up reinventing the wheel. I’ll have to give it another go with fresh eyes.

2 Likes