After you unzipped the file to $folder['path']
you have to manually add all unzipped files to the $_FILES array and do media_handle_upload, etc. for them. You are iterating over it, so you may create a temporary $unzippedfiles array and push all unzipped files into it.
You have to create for each file an entry similar to which it would appear in $_FILES. Especially the files should be put into the default php upload directory ini_get('upload_tmp_dir')
so that the wordpress functions can handle it correctly.
After you have looped the entire $_FILES array once you may replace it with $unzippedfiles and iterate over it doing the attachement stuff.
Here is some code that should handle your problem:
$post_id = wp_insert_post($new_post);
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
function dir_tree($dir) {
//http://www.php.net/manual/de/function.scandir.php#102505
$paths = array();
$stack[] = $dir;
while ($stack) {
$thisdir = array_pop($stack);
if ($dircont = scandir($thisdir)) {
$i=0;
while (isset($dircont[$i])) {
if ($dircont[$i] !== '.' && $dircont[$i] !== '..') {
$current_file = "{$thisdir}/{$dircont[$i]}";
if (is_file($current_file)) {
$paths[] = "{$thisdir}/{$dircont[$i]}";
} elseif (is_dir($current_file)) {
$paths[] = "{$thisdir}/{$dircont[$i]}";
$stack[] = $current_file;
}
}
$i++;
}
}
}
return $paths;
}
if ($_FILES) {
$unzipped = array();
foreach ($_FILES as $fid => $array) {
if ($array['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $array['error'];
}
WP_Filesystem();
$folder = ini_get('upload_tmp_dir')."/unzipped_".basename($array['tmp_name']);
if( ! is_dir( $folder ) ) {
mkdir( $folder );
}
if( unzip_file($array['tmp_name'], $folder ) === True ) {
$filepaths = dir_tree( $folder );
foreach( $filepaths as $k => $filepath ) {
if( is_file($filepath) ) {
$file = array();
$file['name'] = basename( $filepath );
$file['size'] = filesize( $filepath );
$file['tmp_name'] = $filepath;
$unzipped["unzipped_$k"] = $file;
}
}
}
$attach_id = media_handle_upload($fid, $post_id );
update_post_meta($post_id, '_thumbnail_id', $attach_id);
$post_id = wp_update_post();
}
foreach ($unzipped as $file ) {
$attach_id = media_handle_sideload($file,$post_id);
update_post_meta($post_id, '_thumbnail_id', $attach_id);
$post_id = wp_update_post();
}
}