A WordPress-centric search engine for devs and theme authors



media_sideload_image ›

Since2.6.0
Deprecatedn/a
media_sideload_image ( $file, $post_id, $desc = null, $return = 'html' )
Parameters: (4)
  • (string) $file The URL of the image to download.
    Required: Yes
  • (int) $post_id The post ID the media is to be associated with.
    Required: Yes
  • (string) $desc Optional. Description of the image.
    Required: No
    Default: null
  • (string) $return Optional. Accepts 'html' (image tag html) or 'src' (URL), or 'id' (attachment ID). Default 'html'.
    Required: No
    Default: 'html'
Returns:
  • (string|WP_Error) Populated HTML img tag on success, WP_Error object otherwise.
Defined at:
Codex:
Change Log:
  • 4.2.0
  • 4.8.0

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



Source

function media_sideload_image( $file, $post_id, $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'] = 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;
			// If attachment id was requested, return it early.
		} elseif ( $return === 'id' ) {
			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 ( $return === 'src' ) {
			return $src;
		}

		$alt  = isset( $desc ) ? esc_attr( $desc ) : '';
		$html = "<img src='$src' alt='$alt' />";
		return $html;
	} else {
		return new WP_Error( 'image_sideload_failed' );
	}
}