Custom image upload
-
05-11-2019 - |
Question
I'm trying to setup upload for for attachments for my custom post form.
At first I add to my form
tag enctype="multipart/form-data"
For testing purposes I have two upload forms, but in future I'm gonna implement only one form and use jQuery to append as many forms as I want.
<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>
in PHP I use:
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.
}
}
and in functions.php I have functions which should handle this form.
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;
}
everything works pefect if I just upload two images, but If I want to upload only one OR none, I get error my post_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:{}}
I tried inserting: if ($_FILES[$file_handler]['error'] === 4) __return_false(); in functions.php but it does not work, how to tell my script that my form is empty?
Credits: took this form from here
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange