An alternative is to put the upload form <input type="file"> in the front end posting form & process it along / after the rest of the function.
Here is the file input:
<input type="file" id="profile-picture" name="profile-picture[]" size="40" multiple />
Just change the name attribute accordingly. The [] on the attribute value & the multiple is for multiple file upload.
The attaching function :
function attach_uploads($uploads,$post_id = 0){
$files = rearrange($uploads);
if($files[0]['name']==''){
return false;
}
foreach($files as $file){
$upload_file = wp_handle_upload( $file, array('test_form' => false) );
$attachment = array(
'post_mime_type' => $upload_file['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($upload_file['file'])),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $upload_file['file'], $post_id );
$attach_array[] = $attach_id;
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload_file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
return $attach_array;
}
You can find more on the rearrange function here.
And the additional function to attach as post_thumbnail
// put this along the other $_POST
$files = $_FILES['profile-picture'];
// insert attachment, after you have created the new post id → $post_id
$attached_files = attach_uploads($files,$post_id);
// set the first file as post thumbnail
if($attached_files){
set_post_thumbnail( $post_id, $attached_files[0] );
}
Hope this help