从指定的URL下载图像并将其附加到帖子。

原型

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

参数

$file (string) (Required) 要下载的图像的URL。

$post_id (int) (Required) 媒体要关联的帖子ID。

$desc (string) (Optional)  图像描述。

$return (string) (Optional)  接受’html’(图片标记html)或’src’(URL)或’id’(附件ID)。

返回值

(string|WP_Error)  填充HTML img标记成功,

源文件

路径:wp-admin/includes/media.php

<?php
...
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' );
	}
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/media_sideload_image/