Site icon Hip-Hop Website Design and Development

wordpress media library attach files

I have a form to post(custom post type) on frontend.
In this form I use the WordPress media library.
But the problem is that when I upload an image from the media library, it does not attach. Because it does not have any post ID before the form is submitted. So I used the following code.
But this code attaches an image twice. And the featured image does not work.

if (count($error) == 0) {
    $post_id = wp_insert_post(array(
        'post_title' => esc_sql($_POST['title']),
        'post_content' => wp_kses_post($_POST['content']),
        'post_author' => $user_id,
        'post_status' => 'pending',
        'post_type' => 'document',
    ));

    if ($_POST['_file_id']) {
        foreach ($_POST['_file_id'] as $file => $value) {
            $image = wp_get_attachment_image_url($value, "larg");
            $filetype = wp_check_filetype(basename($image), null);
            $wp_upload_dir = wp_upload_dir();
            $attachment = array(
                'guid' => $wp_upload_dir['url'] . '/' . basename($image),
                'post_mime_type' => $filetype['type'],
                'post_title' => preg_replace('/.[^.]+$/', '', basename($image)),
                'post_content' => '',
                'post_status' => 'inherit'
            );
            $image_id = wp_insert_attachment($attachment, $image, $post_id);
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata($image_id, $image);
            wp_update_attachment_metadata($image_id, $attach_data);
            update_post_meta($post_id, '_thumbnail_id', $image_id);
        }
    }
}

Thanks