During WordPress development, there are times when we need to save a file or image from a remote server into the WordPress Media Library so it can be cached or backed up locally. The implementation is straightforward: download the file from the remote server, then insert it into the media library.
Use WordPress download_url() to download the file
WordPress provides a file download function called download_url( $url ), which we can use to download a remote file.
$tmp = download_url( $url );
Use media_handle_sideload() to save the downloaded file into the Media Library
After download_url( $url ) runs, the file only exists as a temporary file. In this step, we need to save that temporary file into the Media Library. Before doing so, we need to obtain a filename for the file. If you do not care about the name, you can also generate one randomly. Then use WordPress’s media_handle_sideload function to save the file into the Media Library.
/**
* Download a remote file to the WordPress server.
* The target remote file must use a file type allowed by WordPress.
*
* @param $url
*
* @return false|int|\WP_Error
*/
function download_remote_file($url){
$tmp = download_url( $url );
$file_array = array();
// Set variables for saving the file
preg_match('/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
$file_array['name'] = basename($matches[0]);
$file_array['tmp_name'] = $tmp;
// If the temporary file failed, delete it
if ( is_wp_error( $tmp ) ) {
@unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
}
// Save the file to the Media Library
$id = media_handle_sideload( $file_array, 0 );
// If saving fails, delete the file
if ( is_wp_error($id) ) {
@unlink($file_array['tmp_name']);
return $id;
}
return false;
}
Pass a remote URL into the function above and it will download the file into the WordPress Media Library, insert the attachment into the media database, and return a media library ID that you can use for further processing.
A simpler option: media_sideload_image()
The approach above can save not only remote images but other file types as well. If you only want to save an image, there is a simpler method: media_sideload_image. You only need a few lines of code.
$url = "http://wordpress.org/about/images/logos/wordpress-logo-stacked-rgb.png";
$post_id = 1;
$desc = "The WordPress Logo";
$image = media_sideload_image($url, $post_id, $desc);
If you use this on a front-end page in WordPress, you need to include the following files:
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
