Submit post and upload image from front-end

If you are talking about the answer i posted here
its simply uploading file in an iframe to achieve “Ajax like” submit.

Now if you already have a form that handles the post submit you can simply add the upload file field input somewhere in your form:

<form ...
...
<input type="file" name="thumbnail" id="thumbnail">
...
...
</form>

make sure that your form has enctype="multipart/form-data" attribute.

then in your form processing script after you create the post (assuming that you are using wp_insert_post();)
keep hold of the post ID in a new var:

$new_post = wp_insert_post($post_array);

and after that add:

            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');
            }
             if ($_FILES) {
                foreach ($_FILES as $file => $array) {
                    if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
                        return "upload error : " . $_FILES[$file]['error'];
                    }
                    $attach_id = media_handle_upload( $file, $new_post );
                }   
            }
            if ($attach_id > 0){
                //and if you want to set that image as Post  then use:
                update_post_meta($new_post,'_thumbnail_id',$attach_id);
            }

and you image will be uploaded and saved as post thumbnail.

Leave a Comment