W3cubDocs

/WordPress

media_sideload_image( string $file, int $post_id, string $desc = null, string $return = 'html' )

Downloads an image from the specified URL and attaches it to a post.

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 value: null

$return

(string) (Optional) Accepts 'html' (image tag html) or 'src' (URL), or 'id' (attachment ID).

Default value: 'html'

Return

(string|WP_Error) Populated HTML img tag on success, WP_Error object otherwise.

More Information

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');

Source

File: wp-admin/includes/media.php

function media_sideload_image( $file, $post_id = 0, $desc = null, $return = 'html' ) {
	if ( ! empty( $file ) ) {

		// Set variables for storage, fix file filename for query strings.
		preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );

		if ( ! $matches ) {
			return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL.' ) );
		}

		$file_array         = array();
		$file_array['name'] = wp_basename( $matches[0] );

		// Download file to temp location.
		$file_array['tmp_name'] = download_url( $file );

		// If error storing temporarily, return the error.
		if ( is_wp_error( $file_array['tmp_name'] ) ) {
			return $file_array['tmp_name'];
		}

		// Do the validation and storage stuff.
		$id = media_handle_sideload( $file_array, $post_id, $desc );

		// If error storing permanently, unlink.
		if ( is_wp_error( $id ) ) {
			@unlink( $file_array['tmp_name'] );
			return $id;
		}

		// Store the original attachment source in meta.
		add_post_meta( $id, '_source_url', $file );

		// If attachment ID was requested, return it.
		if ( 'id' === $return ) {
			return $id;
		}

		$src = wp_get_attachment_url( $id );
	}

	// Finally, check to make sure the file has been saved, then return the HTML.
	if ( ! empty( $src ) ) {
		if ( 'src' === $return ) {
			return $src;
		}

		$alt  = isset( $desc ) ? esc_attr( $desc ) : '';
		$html = "<img src='$src' alt='$alt' />";

		return $html;
	} else {
		return new WP_Error( 'image_sideload_failed' );
	}
}

Changelog

Version Description
5.4.0 The original URL of the attachment is stored in the _source_url post meta value.
5.3.0 The $post_id parameter was made optional.
4.8.0 Introduced the 'id' option within the $return parameter.
4.2.0 Introduced the $return parameter.
2.6.0 Introduced.

© 2003–2019 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/functions/media_sideload_image