media_sideload_image()
Uploads an image to the WP media library from the specified URL and attaches it to a post.
In other words, the function uploads an image from an external URL to the WP media library, attaches it to the specified post and returns <img> or the URL of the uploaded image.
For the function to work in the Front-end the following files are required:
require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/image.php';
If you need to upload any file type (and not only an image), use a similar function: media_handle_sideload().
Hooks from the function
Returns
String|Int|WP_Error.
string- HTML of the img tag, when $return = html (by default).string- URL of the uploaded attachment, when $return = src.int- ID of the uploaded attachment, when $return = id.- WP_Error - error object, with the error message.
Usage
media_sideload_image( $file, $post_id, $desc, $return_type );
- $file(string) (required)
- URL of the image to upload.
- $post_id(int) (required)
- ID of the post to which the uploaded image file will be attached.
0— do not attach. - $desc(string|null)
The image title. If not specified, the title will be taken from the URL or from the image metadata.
Note: This parameter actually sets the attachment "TITLE", not the "DESCRIPTION". There is no way to set a real attachment description using this function.
Default: null
- $return_type(string)
What to return. Can be:
html- the image IMG tagsrc- just the URLid- attachment ID. Since WP 4.8
Default: 'html'
Examples
#1 Download the image file for the post from an external URL
// when we're at the front
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
$url = 'http://s.w.org/style/images/wp-header-logo.png';
$post_id = 3061;
$desc = "WordPress Logo";
$img_tag = media_sideload_image( $url, $post_id, $desc );
if( is_wp_error( $img_tag ) ){
echo $img_tag->get_error_message();
}
else {
// file added
echo $img_tag;
}
The same example, but in a different implementation, is shown in the description of media_handle_sideload() function.
Changelog
| Since 2.6.0 | Introduced. |
| Since 4.2.0 | Introduced the $return_type parameter. |
| Since 4.8.0 | Introduced the 'id' option for the $return_type parameter. |
| Since 5.3.0 | The $post_id parameter was made optional. |
| Since 5.4.0 | The original URL of the attachment is stored in the _source_url post meta value. |
| Since 5.8.0 | Added 'webp' to the default list of allowed file extensions. |