我正在尝试为自定义帖子表单的附件设置上载。
首先,我将form
标签enctype="multipart/form-data"
出于测试目的,我有两个上传表单,但将来我将只实现一个表单,并使用jQuery附加任意多个表单。
<fieldset class="images">
<label for="images">Front of the Bottle</label>
<input type="file" name="image1" id="bottle_front" size="50">
</fieldset>
<fieldset class="images">
<label for="images">Back of the Bottle</label>
<input type="file" name="image2" id="bottle_rear" size="50">
</fieldset>
在PHP中,我使用:
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post_id);
// $newupload returns the attachment id of the file that
// was just uploaded. Do whatever you want with that now.
}
}
和在函数中。我有一些函数可以处理这个表单。
function insert_attachment($file_handler,$post_id,$setthumb=\'false\') {
// check to make sure its a successful upload
if ($_FILES[$file_handler][\'error\'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb) update_post_meta($post_id,\'_thumbnail_id\',$attach_id);
return $attach_id;
}
如果我只上传两张图片,一切都会正常,但如果我只想上传一张或一张都不想上传,我会收到错误消息my post\\u meta db:
O:8:"WP_Error":2:{s:6:"errors";a:1:{s:12:"upload_error";a:1:{i:0;s:21:"No file was uploaded.";}}s:10:"error_data";a:0:{}}
我尝试插入:if($\\u FILES[$file\\u handler][“error”]==4)\\uu return\\u false();在函数中。php但它不工作,如何告诉我的脚本我的表单是空的?
学分:took this form from here
最合适的回答,由SO网友:Rajeev Vyas 整理而成
可能您没有从函数中正确返回,请尝试以下操作,
function insert_attachment($file_handler, $post_id, $setthumb=false) {
// check to make sure its a successful upload
// changes start
if ($_FILES[$file_handler][\'error\'] !== UPLOAD_ERR_OK) {
return __return_false();
}
// changes end
require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb)
update_post_meta($post_id, \'_thumbnail_id\', $attach_id);
return $attach_id;
}