media_handle_sideload

函数
media_handle_sideload ( $file_array, $post_id = 0, $desc = null, $post_data = array() )
参数
  • (string[]) $file_array Array that represents a `$_FILES` upload array.
    Required:
  • (int) $post_id Optional. The post ID the media is associated with.
    Required:
  • (string) $desc Optional. Description of the side-loaded file. Default null.
    Required:
    Default: null
  • (array) $post_data Optional. Post data to override. Default empty array.
    Required:
    Default: array()
返回值
  • (int|WP_Error) The ID of the attachment or a WP_Error on failure.
定义位置
相关方法
media_handle_uploadwp_handle_sideloadwp_embed_handler_videomedia_sideload_imagewp_handle_upload
引入
2.6.0
弃用
-

media_handle_sideload函数是用来处理不是通过表单提交的文件的上传。它通常被需要以编程方式上传文件的插件或主题所使用,而不需要用户与表单交互。

处理一个侧面加载的文件,与上传的文件由media_handle_upload()处理的方式相同。

function media_handle_sideload( $file_array, $post_id = 0, $desc = null, $post_data = array() ) {
	$overrides = array( 'test_form' => false );

	if ( isset( $post_data['post_date'] ) && substr( $post_data['post_date'], 0, 4 ) > 0 ) {
		$time = $post_data['post_date'];
	} else {
		$post = get_post( $post_id );
		if ( $post && substr( $post->post_date, 0, 4 ) > 0 ) {
			$time = $post->post_date;
		} else {
			$time = current_time( 'mysql' );
		}
	}

	$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( '/.[^.]+$/', '', wp_basename( $file ) );
	$content = '';

	// Use image exif/iptc data for title and caption defaults if possible.
	$image_meta = wp_read_image_metadata( $file );

	if ( $image_meta ) {
		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.
	$attachment_id = wp_insert_attachment( $attachment, $file, $post_id, true );

	if ( ! is_wp_error( $attachment_id ) ) {
		wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
	}

	return $attachment_id;
}

常见问题

FAQs
查看更多 >