wppaste
WordPress

media_sideload_image( string $file, int $post_id = 0, string $desc = null, string $return_type = 'html' ): string|int|WP_Error

Since
2.6.0, 4.2.0, 4.8.0, 5.3.0, 5.4.0, 5.8.0
Source
wp-admin/includes/media.php:1033
Downloads an image from the specified URL, saves it as an attachment, and optionally attaches it to a post.

Compatibility

WordPress
since 5.8.0
PHP
7.4–8.6-dev
  • 6.7.7
  • 6.8.8
  • 6.9.7
  • 7.0.4
  • 7.1.0

Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.

Parameters

$filestring
The URL of the image to download.
$post_idintoptional
The post ID the media is to be associated with.Default: 0
$descstringoptional
Description of the image.Default: null
$return_typestringoptional
Accepts 'html' (image tag html) or 'src' (URL), or 'id' (attachment ID). Default 'html'.Default: 'html'

Return value

string|int|WP_Error
Populated HTML img tag, attachment ID, or attachment source on success, WP_Error object otherwise.

Performance profile

How much work a call to media_sideload_image() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.

Cost class
Expensive

Reaches an outbound HTTP request via wp_safe_remote_get().

Scaling
Constant

No loop in the body: the same number of instructions runs whatever you pass in.

Instructions
11–85

Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 109.

Plugin surface
1 hook

Third-party callbacks on 'image_sideload_extensions' run inside this call, and their cost is not bounded by anything here.

Called by
0

Nothing in core calls this; the cost is only what you spend yourself.

What it touches

  • hookthird-party callbacksapply_filters()called directly
  • filesystemfilesystem accessunlink()called directly
  • httpoutbound HTTP requestwp_safe_remote_get()one call below media_sideload_image()
  • querycontent queryget_post()one call below media_sideload_image()

Further down the call graph this can also reach option, serialize, cache and transient. Those are the worst case, several calls deep and usually down an error path, not what a normal call pays.

What one call costs · 8 distinct outcomes

One number would be a lie: the work depends on which branch runs. These are every distinct cost media_sideload_image() can have, taken from its control-flow graph on PHP 8.5.

WhenInstructionsCalls it makes
empty($file)11–20none
empty($file) && !empty($src) && $return_type !== "src" && isset($desc)24esc_attr()
!empty($file)35apply_filters(), array_map(), preg_match(), __()
!empty($file) && is_wp_error()48apply_filters(), array_map(), preg_match(), wp_basename(), download_url(), is_wp_error()
!empty($file)63apply_filters(), array_map(), preg_match(), wp_basename(), download_url(), is_wp_error(), media_handle_sideload(), is_wp_error(), unlink()
!empty($file) && !is_wp_error() && $return_type === "id"64apply_filters(), array_map(), preg_match(), wp_basename(), download_url(), is_wp_error(), media_handle_sideload(), is_wp_error(), add_post_meta()
!empty($file) && !is_wp_error() && $return_type !== "id"72–81apply_filters(), array_map(), preg_match(), wp_basename(), download_url(), is_wp_error(), media_handle_sideload(), is_wp_error(), add_post_meta(), wp_get_attachment_url()
!empty($file) && !is_wp_error() && $return_type !== "id" && !empty($src) && $return_type !== "src" && isset($desc)85apply_filters(), array_map(), preg_match(), wp_basename(), download_url(), is_wp_error(), media_handle_sideload(), is_wp_error(), add_post_meta(), wp_get_attachment_url(), esc_attr()

Across PHP versions

PHPCompiledExecutedBranchesNotes
8.6-dev10811–8481 fewer instruction than PHP 8.5
8.510911–858
8.410911–8583 fewer instructions than PHP 8.3
8.311211–888
8.211211–888
8.111211–888
7.411211–888

An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.

Hooks and filters fired · 1

One hook fires while media_sideload_image() runs, in this order:

  1. apply_filters( image_sideload_extensions )filterline 1056 (+23 into the body)

    Filters the list of allowed file extensions when sideloading an image from a URL.

Uses · 10

Source code

function media_sideload_image( $file, $post_id = 0, $desc = null, $return_type = 'html' ) {	if ( ! empty( $file ) ) { 		$allowed_extensions = array( 'jpg', 'jpeg', 'jpe', 'png', 'gif', 'webp' ); 		/**		 * Filters the list of allowed file extensions when sideloading an image from a URL.		 *		 * The default allowed extensions are:		 *		 *  - `jpg`		 *  - `jpeg`		 *  - `jpe`		 *  - `png`		 *  - `gif`		 *  - `webp`		 *		 * @since 5.6.0		 * @since 5.8.0 Added 'webp' to the default list of allowed file extensions.		 *		 * @param string[] $allowed_extensions Array of allowed file extensions.		 * @param string   $file               The URL of the image to download.		 */		$allowed_extensions = apply_filters( 'image_sideload_extensions', $allowed_extensions, $file );		$allowed_extensions = array_map( 'preg_quote', $allowed_extensions ); 		// Set variables for storage, fix file filename for query strings.		preg_match( '/[^\?]+\.(' . implode( '|', $allowed_extensions ) . ')\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_type ) {			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_type ) {			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

Introduced in 4.8.0. Unchanged from 6.7.7 through 7.1.0.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 7.1.0

Signature, return type and hooks compared across 5 parsed releases.

5.8.0
Added 'webp' to the default list of allowed file extensions.from the docblock
5.4.0
The original URL of the attachment is stored in the _source_url post meta value.from the docblock
5.3.0
The $post_id parameter was made optional.from the docblock
4.8.0
Introduced the 'id' option for the $return_type parameter.from the docblock
4.2.0
Introduced the $return_type parameter.from the docblock
2.6.0
Introduced.from the docblock

About this page

Parsed data
Generated from the wordpress-develop 7.1.0 tag, from src/wp-admin/includes/media.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.