The media_sideload_image() WordPress PHP function downloads an image from the specified URL, saves it as an attachment, and optionally attaches it to a post.
Usage
$url = "https://example.com/image.jpg"; $post_id = 1; $desc = "Example image"; $return_type = 'html'; $image = media_sideload_image($url, $post_id, $desc, $return_type);
Parameters
$file(string) Required: The URL of the image to download.$post_id(int) Optional: The post ID the media is to be associated with.$desc(string) Optional: Description of the image. Default: null$return_type(string) Optional: Accepts ‘html’ (image tag html) or ‘src’ (URL), or ‘id’ (attachment ID). Default ‘html’.
More information
See WordPress Developer Resources: media_sideload_image
Examples
Basic Usage
Download an image and attach it to a post with a custom description.
$url = "https://example.com/image.jpg"; $post_id = 1; $desc = "Example image"; $image = media_sideload_image($url, $post_id, $desc);
Return Image URL
Download an image and return the image URL instead of the HTML.
$url = "https://example.com/image.jpg"; $post_id = 1; $desc = "Example image"; $image_url = media_sideload_image($url, $post_id, $desc, 'src');
Return Attachment ID
Download an image and return the attachment ID instead of the HTML.
$url = "https://example.com/image.jpg"; $post_id = 1; $desc = "Example image"; $attachment_id = media_sideload_image($url, $post_id, $desc, 'id');
Add Custom File Extension
Download a custom file type (e.g., mp3) by adding it to the accepted extensions.
add_filter('image_sideload_extensions', function ($accepted_extensions) {
$accepted_extensions = 'mp3';
return $accepted_extensions;
});
Find Attachment ID from Image URL
Find the attachment ID from the image URL after using the media_sideload_image() function.
function fetch_attachment_post_id_from_src($image_src) {
global $wpdb;
$query = "SELECT ID FROM {$wpdb->posts} WHERE guid=%s";
$id = $wpdb->get_var($wpdb->prepare($query, $image_src));
return $id;
}
$url = "https://example.com/image.jpg";
$post_id = 1;
$desc = "Example image";
$image_url = media_sideload_image($url, $post_id, $desc, 'src');
$attachment_id = fetch_attachment_post_id_from_src($image_url);