media_sideload_image()

最后更新于:2021-11-27 14:45:02

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

Downloads an image from the specified URL, saves it as an attachment, and optionally attaches it to a post.

参数

$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’

响应

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

源文件

文件: gc-admin/includes/media.php

function media_sideload_image( $file, $post_id = 0, $desc = null, $return = '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`
		 *
		 * @since 5.6.0
		 *
		 * @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 GC_Error( 'image_sideload_failed', __( 'Invalid image URL.' ) );
		}

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

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

		// If error storing temporarily, return the error.
		if ( is_gc_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_gc_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 = gc_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='https://docs.gechiui.com/functions/media_sideload_image/$src' alt='$alt' />";

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