Thanks @Judd Franklin for the directions. I was also missing $submission->uploaded_files();
.
Here is the working code for those who are looking for the same answer:
function image_form_to_featured_image( $contact_form ) {
$submission = WPCF7_Submission::get_instance();
$posted_data = $submission->get_posted_data();
// Creating a new post with contact form values
$args = array(
'post_type' => 'projects',
'post_status'=> 'draft',
'post_title'=> wp_strip_all_tags( $posted_data['title'] ),
'post_content'=> wp_strip_all_tags( $posted_data['pitch'] ),
);
$post_id = wp_insert_post($args);
// Retrieving and inserting uploaded image as featured image
$uploadedFiles = $submission->uploaded_files();
if( isset($posted_data['featured']) ){
$featuredUpload = wp_upload_bits($posted_data['featured'], null, file_get_contents($uploadedFiles['featured']));
require_once(ABSPATH . 'wp-admin/includes/admin.php');
$filename = $featuredUpload['file'];
$attachment = array(
'post_mime_type' => $featuredUpload['type'],
'post_parent' => $post_id,
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
set_post_thumbnail( $post_id, $attachment_id );
}
}
}
add_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' );