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.