我有一个用于编辑自定义帖子的自定义表单,此表单供前端用户编辑其帖子和相应的附件。对于附件部分,我在表单中有两个输入文件元素,可以上传图像和视频,我到达下面的PHP代码来捕获上传的附件。
if ($_FILES) {
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK || $_FILES[$file]['error'] === UPLOAD_ERR_NO_FILE) {
$ermg = "upload error : " . $_FILES[$file]['error'];
continue;
} else {
$attach_id = media_handle_upload($file, $post_id);
$type = get_post_mime_type($attach_id);
if ($type === 'image/jpeg' || $type === 'image/png') {
update_post_meta($new_post, '_thumbnail_id', $attach_id);
} elseif ($type === 'video/mp4' || $type === 'video/quickime') {
update_post_meta($new_post, '_video_id', $attach_id);
}
}
return $ermg;
}
}
问题在于,如果两个附件同时上传,我的代码不会只捕获一个附件,而上传单个附件的工作正常。
除此之外还有一个问题,我看到一个新的未知附件,每次上传发生时媒体库中都没有形成标题,下面是屏幕截图,不期望这个新的未知附件。有人可以帮忙吗?
答案 0 :(得分:0)
试试这个:(在function.php中)
require_once(ABSPATH.'wp-admin/includes/admin.php');
if ($_FILES)
{
foreach ($_FILES as $file => $array)
{
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) )
{
$ermg = "upload error : " . $_FILES[$file]['error'];
continue;
}
else
{
$filename=$file_return['file'];
$type=$file_return['type'];
$attachment=array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id=wp_insert_attachment($attachment, $file_return['url']);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data=wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata($attachment_id,$attachment_data);
if ($type === 'image/jpeg' || $type === 'image/png') {
update_post_meta($new_post, '_thumbnail_id', $attachment_id);
} elseif ($type === 'video/mp4' || $type === 'video/quickime') {
update_post_meta($new_post, '_video_id', $attachment_id);
}
}
return $ermg;
}
}