media_handle_upload()
云策文档标注
概述
media_handle_upload() 是 WordPress 核心函数,用于处理通过 POST 请求上传的文件,并创建对应的附件文章。它封装了文件上传、元数据提取和附件创建过程,支持音频和图像文件的特殊处理。
关键要点
- 函数接收四个参数:$file_id($_FILES 数组索引)、$post_id(关联文章 ID,可为 0)、$post_data(附件数据覆盖数组)和 $overrides(上传行为覆盖数组)。
- 内部调用 wp_handle_upload() 处理文件上传,支持通过 $overrides 参数自定义错误处理、文件名唯一性等行为。
- 自动根据文件类型(音频或图像)提取元数据(如 ID3 标签或 EXIF/IPTC 数据),用于设置附件标题、内容等字段。
- 通过 wp_insert_attachment() 创建附件文章,并调用 wp_update_attachment_metadata() 生成元数据和子尺寸(如图像)。
- 返回附件 ID 或 WP_Error 对象,失败时返回错误信息。
- 使用时需确保表单设置 enctype="multipart/form-data",否则 $_FILES 可能为空。
代码示例
// 前端表单示例
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_image_upload" id="my_image_upload" />
<input type="submit" value="Upload Image" name="submit" />
</form>
// 保存附件代码
if ( isset( $_FILES['my_image_upload'] ) ) {
$attachment_id = media_handle_upload( 'my_image_upload', 0 );
if ( is_wp_error( $attachment_id ) ) {
// 处理错误
} else {
// 附件创建成功
}
}注意事项
- 函数依赖于 $_FILES 数组,必须通过 POST 请求上传文件。
- 对于音频文件,会自动从 ID3 标签提取元数据;对于图像文件,会从 EXIF/IPTC 数据提取标题和说明。
- 设置 $post_id 为 0 可创建独立附件,不与特定文章关联。
- 上传大文件时,生成图像子尺寸可能导致超时或内存错误,需注意服务器配置。
原文内容
Saves a file submitted from a POST request and create an attachment post for it.
Parameters
$file_idstringrequired-
Index of the
$_FILESarray that the file was sent. $post_idintrequired-
The post ID of a post to attach the media item to. Required, but can be set to 0, creating a media item that has no relationship to a post.
$post_dataarrayoptional-
Overwrite some of the attachment.
Default:
array() $overridesarrayoptional-
Override the wp_handle_upload() behavior.
More Arguments from wp_handle_upload( … $overrides )
An array of override parameters for this file, or boolean false if none are provided.
upload_error_handlercallableFunction to call when there is an error during the upload process.
See wp_handle_upload_error().unique_filename_callbackcallableFunction to call when determining a unique file name for the file.
See wp_unique_filename().upload_error_stringsstring[]The strings that describe the error indicated in$_FILES[{form field}]['error'].test_formboolWhether to test that the$_POST['action']parameter is as expected.test_sizeboolWhether to test that the file size is greater than zero bytes.test_typeboolWhether to test that the mime type of the file is as expected.mimesstring[]Array of allowed mime types keyed by their file extension regex.
Default:
array( => false)
Source
function media_handle_upload( $file_id, $post_id, $post_data = array(), $overrides = array( 'test_form' => false ) ) {
$time = current_time( 'mysql' );
$post = get_post( $post_id );
if ( $post ) {
// The post date doesn't usually matter for pages, so don't backdate this upload.
if ( 'page' !== $post->post_type && substr( $post->post_date, 0, 4 ) > 0 ) {
$time = $post->post_date;
}
}
$file = wp_handle_upload( $_FILES[ $file_id ], $overrides, $time );
if ( isset( $file['error'] ) ) {
return new WP_Error( 'upload_error', $file['error'] );
}
$name = $_FILES[ $file_id ]['name'];
$ext = pathinfo( $name, PATHINFO_EXTENSION );
$name = wp_basename( $name, ".$ext" );
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$title = sanitize_text_field( $name );
$content = '';
$excerpt = '';
if ( preg_match( '#^audio#', $type ) ) {
$meta = wp_read_audio_metadata( $file );
if ( ! empty( $meta['title'] ) ) {
$title = $meta['title'];
}
if ( ! empty( $title ) ) {
if ( ! empty( $meta['album'] ) && ! empty( $meta['artist'] ) ) {
/* translators: 1: Audio track title, 2: Album title, 3: Artist name. */
$content .= sprintf( __( '"%1$s" from %2$s by %3$s.' ), $title, $meta['album'], $meta['artist'] );
} elseif ( ! empty( $meta['album'] ) ) {
/* translators: 1: Audio track title, 2: Album title. */
$content .= sprintf( __( '"%1$s" from %2$s.' ), $title, $meta['album'] );
} elseif ( ! empty( $meta['artist'] ) ) {
/* translators: 1: Audio track title, 2: Artist name. */
$content .= sprintf( __( '"%1$s" by %2$s.' ), $title, $meta['artist'] );
} else {
/* translators: %s: Audio track title. */
$content .= sprintf( __( '"%s".' ), $title );
}
} elseif ( ! empty( $meta['album'] ) ) {
if ( ! empty( $meta['artist'] ) ) {
/* translators: 1: Audio album title, 2: Artist name. */
$content .= sprintf( __( '%1$s by %2$s.' ), $meta['album'], $meta['artist'] );
} else {
$content .= $meta['album'] . '.';
}
} elseif ( ! empty( $meta['artist'] ) ) {
$content .= $meta['artist'] . '.';
}
if ( ! empty( $meta['year'] ) ) {
/* translators: Audio file track information. %d: Year of audio track release. */
$content .= ' ' . sprintf( __( 'Released: %d.' ), $meta['year'] );
}
if ( ! empty( $meta['track_number'] ) ) {
$track_number = explode( '/', $meta['track_number'] );
if ( is_numeric( $track_number[0] ) ) {
if ( isset( $track_number[1] ) && is_numeric( $track_number[1] ) ) {
$content .= ' ' . sprintf(
/* translators: Audio file track information. 1: Audio track number, 2: Total audio tracks. */
__( 'Track %1$s of %2$s.' ),
number_format_i18n( $track_number[0] ),
number_format_i18n( $track_number[1] )
);
} else {
$content .= ' ' . sprintf(
/* translators: Audio file track information. %s: Audio track number. */
__( 'Track %s.' ),
number_format_i18n( $track_number[0] )
);
}
}
}
if ( ! empty( $meta['genre'] ) ) {
/* translators: Audio file genre information. %s: Audio genre name. */
$content .= ' ' . sprintf( __( 'Genre: %s.' ), $meta['genre'] );
}
// Use image exif/iptc data for title and caption defaults if possible.
} elseif ( str_starts_with( $type, 'image/' ) ) {
$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'] ) ) {
$excerpt = $image_meta['caption'];
}
}
}
// 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_excerpt' => $excerpt,
),
$post_data
);
// This should never be set as it would then overwrite an existing attachment.
unset( $attachment['ID'] );
// Save the data.
$attachment_id = wp_insert_attachment( $attachment, $file, $post_id, true );
if ( ! is_wp_error( $attachment_id ) ) {
/*
* Set a custom header with the attachment_id.
* Used by the browser/client to resume creating image sub-sizes after a PHP fatal error.
*/
if ( ! headers_sent() ) {
header( 'X-WP-Upload-Attachment-ID: ' . $attachment_id );
}
/*
* The image sub-sizes are created during wp_generate_attachment_metadata().
* This is generally slow and may cause timeouts or out of memory errors.
*/
wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
}
return $attachment_id;
}
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |
Skip to note 3 content
Codex
Upload an attachment from a form on the front end of the site.
The upload form might look like this:
<form id="featured_upload" method="post" action="#" enctype="multipart/form-data"> <input type="file" name="my_image_upload" id="my_image_upload" multiple="false" /> <input type="hidden" name="post_id" id="post_id" value="55" /> <input id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Upload" /> </form>The code to save the attachment:
Skip to note 4 content
M@X
Be sure you use attribute enctype=”multipart/form-data” at your form.
If you missed it, the $_FILES would be empty.