Adding featured image to a new post using front-end form?

Updated

I’m not sure how to do it without ContactForm 7 plugin, but here’s my past code on how to do it in CF7:

Assuming your file field is [file your-file].

add_action( 'wpcf7_before_send_mail', 'my_cf7_save_featured_image', 10, 2 ); 

function my_cf7_save_featured_image( $instance, $result ) {
  require_once( ABSPATH . 'wp-admin/includes/image.php' );
  require_once( ABSPATH . 'wp-admin/includes/admin.php' );  

  // Get submission data instead of using $_POST
  $sub = \WPCF7_Submission::get_instance();
  $data = $sub->get_posted_data();

  // Create post
  $my_post = array(
    'post_title' => $data['title'],
    'post_content' => $data['description'],
    'post_status' => 'publish', 
    'post_type' => 'post',
  );
    
  $post_id = wp_insert_post($my_post);
  add_post_meta( $post_id, 'address1', $data['address1'], false );
  
  // extract submitted file
  $uploaded_files = $sub->uploaded_files();
  $image_name = $data['your-file'];
  $image_location = $uploaded_files['your-file'];
  $image_content = file_get_contents( $image_location );

  // set upload path
  $dir = wp_upload_dir();
  $upload = wp_upload_bits( $image_name, null, $image_content );
  $filename = $upload['file'];
  
  $wp_filetype = wp_check_filetype( basename( $filename ), null );

  $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
        'post_content' => '',
        'post_status' => 'inherit',
  );

  // start upload and attach to post
  $attach_id = wp_insert_attachment( $attachment, wp_slash( $filename ), $post_id );

  // update image metadata
  $attach_data = wp_generate_attachment_metadata( $attach_id, wp_slash( $filename ) );
  wp_update_attachment_metadata( $attach_id, $attach_data );
}