front end post with multiple upload images?

the multiple="multiple" or multiple="" attribute of input file tag is fairly new and not widely supported cross browser but if that is the way you want to go,

try this:

<form  ...
   <input type="file" id="image" name="image[]" onchange="updateList();" multiple="multiple" >
   <ul id="file_list"></ul>
</form>
<script>
function updateList(){
    //get the input and UL list
    var input = document.getElementById('image');
    var list = document.getElementById('file_list');

    //empty list for now...
    while (list.hasChildNodes()) {
      list.removeChild(ul.firstChild);
    }

    //for every file...
    for (var x = 0; x < input.files.length; x++) {
      //add to list
      var li = document.createElement('li');
      li.innerHTML = 'File ' + (x + 1) + ':  ' + input.files[x].name;
      list.append(li);
    }
}
</script>

now when the files are uploaded you need to use a fix to the array in order to use that function, so use these function from Golden Apples

function fix_file_array(&$files) {
    $names = array(
        'name' => 1,
        'type' => 1,
        'tmp_name' => 1,
        'error' => 1,
        'size' => 1
    );
    foreach ($files as $key => $part) {
        // only deal with valid keys and multiple files
        $key = (string) $key;
        if (isset($names[$key]) && is_array($part)) {
            foreach ($part as $position => $value) {
                $files[$position][$key] = $value;
            }
            // remove old key reference
            unset($files[$key]);
        }
    }
}


function insert_attachment($file_handler,$post_id,$setthumb='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_sideload( $file_handler, $post_id );
    if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
    return $attach_id;
}

and once you have this function then you can do this:

if ($_FILES) {
    fix_file_array($_FILES[$name]);
    foreach ($_FILES[$name] as $file => $fileitem){
        $newupload = insert_attachment($fileitem,$real_post_id);
    }
}

which should work

Leave a Comment