media_handle_sideload()
云策文档标注
概述
media_handle_sideload() 函数用于处理侧载文件,类似于 media_handle_upload() 处理上传文件的方式。它允许将服务器上的文件或通过URL获取的文件添加到媒体库,并生成附件元数据。
关键要点
- 函数接受 $file_array(必需,类似 $_FILES 数组)、$post_id(可选,关联的帖子ID)、$desc(可选,文件描述)和 $post_data(可选,覆盖帖子数据)作为参数。
- 返回附件ID或 WP_Error 对象,用于指示成功或失败。
- 内部使用 wp_handle_sideload() 处理文件,并调用 wp_insert_attachment() 和 wp_update_attachment_metadata() 创建附件。
- 支持从图像元数据(如EXIF/IPTC)自动提取标题和描述。
- 与 media_handle_upload() 的主要区别在于:media_handle_sideload() 用于处理服务器端文件,而 media_handle_upload() 用于处理表单上传的文件。
代码示例
$file_array = array(
'name' => basename( $url ),
'tmp_name' => $tmp
);
$post_id = '0';
$id = media_handle_sideload( $file_array, $post_id );
if ( is_wp_error( $id ) ) {
@unlink( $file_array['tmp_name'] );
return $id;
}
$value = wp_get_attachment_url( $id );注意事项
- 在插件中使用此函数时,需要包含核心文件:media.php、file.php 和 image.php。
- 确保 $file_array 正确模拟 $_FILES 数组结构,以避免上传错误。
- 函数会自动处理错误检查,如文件下载失败或上传问题,返回 WP_Error 对象。
原文内容
Handles a side-loaded file in the same way as an uploaded file is handled by media_handle_upload() .
Parameters
$file_arraystring[]required-
Array that represents a
$_FILESupload array. $post_idintoptional-
The post ID the media is associated with.
$descstringoptional-
Description of the side-loaded file.
Default:
null $post_dataarrayoptional-
Post data to override.
Default:
array()
Source
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;
}
Skip to note 5 content
Codex
Example
basename( $url ), 'tmp_name' => $tmp ); /** * Check for download errors * if there are error unlink the temp file name */ if ( is_wp_error( $tmp ) ) { @unlink( $file_array[ 'tmp_name' ] ); return $tmp; } /** * now we can actually use media_handle_sideload * we pass it the file array of the file to handle * and the post id of the post to attach it to * $post_id can be set to '0' to not attach it to any particular post */ $post_id = '0'; $id = media_handle_sideload( $file_array, $post_id ); /** * We don't want to pass something to $id * if there were upload errors. * So this checks for errors */ if ( is_wp_error( $id ) ) { @unlink( $file_array['tmp_name'] ); return $id; } /** * No we can get the url of the sideloaded file * $value now contains the file url in WordPress * $id is the attachment id */ $value = wp_get_attachment_url( $id ); // Now you can do something with $value (or $id)Skip to note 6 content
Daniel Davis
For those wondering about the difference between
media_handle_sideload()andmedia_handle_upload():media_handle_upload()is used to handle file uploads that come from a form submission ($_FILESarray, typically from an HTML form). It expects a form’s file input field’s name and the ID of the post to attach the uploaded media to.On the other hand,
media_handle_sideload()is used when you have a file that exists on the server’s file system (or accessible by URL) and you want to add it to the Media Library and generate the appropriate sizes and metadata for it. You would use this when you’re fetching images from another server or handling images that you’ve created or manipulated on the server.Skip to note 7 content
Aurovrata Venet
If you need to use this function in a plugin you will need to include the following core files,
require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/image.php';Skip to note 8 content
Codex
Usage