I have a CPT "Annonce" which is supposed to have four attached images. Now I building a frontend form to allow users to submit posts with four image upload fields. When I try to submit the form with multiple images, only the last image appears as featured in the dashboard. I see the other images in Media section but not in the post edit page so I can change or delete theme.
I'm using this code in page-post.php:
if ( $_FILES ) {
$files = $_FILES['upload_attachment'];
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_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post_id);
}
}
}
}
...
<label for="postPhoto1">Photo 1 :</label>
<input type="file" name="upload_attachment[]" id="postPhoto1">
<label for="postPhoto1">Photo 2 :</label>
<input type="file" name="upload_attachment[]" id="postPhoto2">
and in functions.php I have this function:
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;
}
Using this form the images are successfully uploaded but only last image get set as featured image, and I want to show other images in the post edit page too.
any help?
Try this
You can install advanced custom fields plugin,create as many image fields as you want,and then use it in frontend with the method described in documentation. http://www.advancedcustomfields.com/resources/tutorials/creating-a-front-end-form/
This method is tested and working by me in wordpress 3.4.2, later editions had problems with uploading from frontend.