Add image to post

Hey I had the same problem about 4 5 days , until I found this code , try some tweaks and see if works 🙂

#Upload and Create attachment
        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');
        }
            $upload = wp_upload_bits( $_FILES['file']['name'], null, file_get_contents( $_FILES['file']['tmp_name'] ) );
            $wp_filetype = wp_check_filetype( basename( $upload['file'] ), null );
            $check = getimagesize($_FILES["file"]["tmp_name"]);
            if($check !== false) {
            $uploadOk = 1;
                } else {
                echo "File is not an image.";
            $uploadOk = 0;
                wp_trash_post( $post_id  );
            }

            $wp_upload_dir = wp_upload_dir();
            $attachment = array(
                'guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path( $upload['file'] ),
                'post_mime_type' => $wp_filetype['type'],
                'post_title' => preg_replace('/\.[^.]+$/', '', basename( $upload['file'] )),    
                'post_content' => '',
                'post_author' => $user_id,
                'post_status' => 'inherit'
            );
            $attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id );
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
            wp_update_attachment_metadata( $attach_id, $attach_data );
    #Upload and Create attachment

    #Use attachment
            update_post_meta( $post_id, '_thumbnail_id', $attach_id );
    #Use attachment