我在前端有一个表单,允许用户根据需要上传多个图像和其他文件类型。要处理我遵循的多个文件数组this answer 这里是相关的。
PHP
global $post;
if ($_FILES) {
$files = $_FILES[\'upload\'];
foreach ($files[\'name\'] as $key => $value) {
if ($files[\'name\'][$key]) {
$file = array(
\'name\' => $files[\'name\'][$key],
\'type\' => $files[\'type\'][$key],
\'tmp_name\' => $files[\'tmp_name\'][$key],
\'error\' => $files[\'error\'][$key],
\'size\' => $files[\'size\'][$key]
);
$_FILES = array("upload" => $file);
foreach ($_FILES as $file => $array) {
$newupload = wp_insert_attachment($file,$post->ID);
}
}
}
}
HTML 请注意,我的表单允许多个图像数组,例如。
upload[]
<form method="post" id="attachment--form" action="" enctype="multipart/form-data" >
<input type="file" multiple="true" name="upload[]">
<?php wp_nonce_field(\'upload_attachments_nonce\',\'secure_upload\'); ?>
<input type="submit" id="upload_attachments_button" name="upload_attachments" value="UPLOAD">
<form>
我想使用本机wordpress函数检查文件类型
wp_check_filetypes, 《法典》对此没有说太多。请帮我举个例子。
最合适的回答,由SO网友:gurung 整理而成
终于弄明白了。如果文件类型不允许,此代码将引发错误。希望这能帮助一些新手节省一些时间。
global $post;//http://wordpress.stackexchange.com/questions/39753/
if ($_FILES) {
$files = $_FILES[\'upload\'];
foreach ($files[\'name\'] as $key => $value) {
if ($files[\'name\'][$key]) {
$file = array(
\'name\' => $files[\'name\'][$key],
\'type\' => $files[\'type\'][$key],
\'tmp_name\' => $files[\'tmp_name\'][$key],
\'error\' => $files[\'error\'][$key],
\'size\' => $files[\'size\'][$key]
);
$uploaded_file_type = $files[\'type\'][$key];
$allowed_file_types = array(\'image/jpg\', \'image/jpeg\', \'application/pdf\');
if(in_array($uploaded_file_type, $allowed_file_types)) {
//if in array run the attachment function
$_FILES = array("upload" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post_id);
}
} else { // wrong file type
$upload_error .= "Invalid File Type. <br />";
}
}
}
}