WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/media sideload image

Description

Download an image from the specified URL and attach it to a post.

Usage

 <?php media_sideload_image($file$post_id$desc); ?> 

Parameters

$file
(string) (required) URL of the image to download.
Default: None
$post_id
(int) (required) The post ID the media is to be attached to.
Default: None
$desc
(string) (optional) Description of the image.
Default: null

Return Value

(string|WP_Error)
Either a string of a populated HTML img tag on success, or a WP_Error on failure.

Examples

Default Usage

<?php 
$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);
?>

Change Log

Since: 2.6.0

Source File

media_sideload_image() is located in wp-admin/includes/media.php.

Notes

If you want to use this function outside of the context of /wp-admin/ (typically if you are writing a more advanced custom importer script) you need to include media.php and depending includes:

require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');

Related

Upload Functions: media_handle_upload(), media_handle_sideload(), wp_handle_upload(), wp_import_handle_upload(), wp_handle_sideload(), media_sideload_image()

Attachment Functions:

get_children(), get attached media(), the_attachment_link(), get_attachment_link(), wp_get_attachment_link(), wp_get_attachment_image(), wp_get_attachment_image_src(), wp_get_attachment_url(), wp_get_attachment_thumb_file(), wp_get_attachment_thumb_url(), is_attachment(), wp_get_attachment_metadata()

See also index of Function Reference and index of Template Tags.