处理侧载文件的方式与上载文件由media_handle_upload()处理的方式相同。

原型

media_handle_sideload( array $file_array, int $post_id, string $desc = null, array $post_data = array() )

参数

$file_array (array) (Required) 数组类似于$ _FILES上传数组。

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

$desc (string) (Optional)  侧载文件的描述。

$post_data (array) (Optional)  发布要覆盖的数据。

返回值

(int|object)  附件的ID或

源文件

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

<?php
...
function media_handle_sideload( $file_array, $post_id, $desc = null, $post_data = array() ) {
	$overrides = array('test_form'=>false);
	$time = current_time( 'mysql' );
	if ( $post = get_post( $post_id ) ) {
		if ( substr( $post->post_date, 0, 4 ) > 0 )
			$time = $post->post_date;
	}
	$file = wp_handle_sideload( $file_array, $overrides, $time );
	if ( isset($file['error']) )
		return new WP_Error( 'upload_error', $file['error'] );
	$url = $file['url'];
	$type = $file['type'];
	$file = $file['file'];
	$title = preg_replace('/.[^.]+$/', '', basename($file));
	$content = '';
	// Use image exif/iptc data for title and caption defaults if possible.
	if ( $image_meta = wp_read_image_metadata( $file ) ) {
		if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) )
			$title = $image_meta['title'];
		if ( trim( $image_meta['caption'] ) )
			$content = $image_meta['caption'];
	}
	if ( isset( $desc ) )
		$title = $desc;
	// Construct the attachment array.
	$attachment = array_merge( array(
		'post_mime_type' => $type,
		'guid' => $url,
		'post_parent' => $post_id,
		'post_title' => $title,
		'post_content' => $content,
	), $post_data );
	// This should never be set as it would then overwrite an existing attachment.
	unset( $attachment['ID'] );
	// Save the attachment metadata
	$id = wp_insert_attachment($attachment, $file, $post_id);
	if ( !is_wp_error($id) )
		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
	return $id;
}
...
?>

其他

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