How to save an image to the library from CF7?

Hi all. Try using CF7 from the front to create a post and attach a featured image.
Media_handle_upload but all the time returns the error Specified file failed upload test.
The same code is not using CF7, but just using samopisny the form works and the picture is filled in to the library. But really really do not want to write the validation, sending emails and ajax the form submission.

Here is the code:

add_action('wpcf7_before_send_mail', 'create_review_post');

create_review_post function($form) {

 $submission = WPCF7_Submission::get_instance();

 if ( $submission ) {

 if (319 == $form->id()) {


 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');
}

 $posted_data = $submission->get_posted_data();

 $review = array(
 'post_title' => wp_strip_all_tags($posted_data['title']),
 'post_content' => $posted_data['content'],
 'post_excerpt' => ",
 'post_status' => 'pending',
 'post_author' => 1,
 'post_type' => 'review'
);

 $new_review_id = wp_insert_post( $review );

 if($new_review_id > 0) {

 if ($_FILES) {
 $attach_id = media_handle_upload('avatar', $new_review_id );
 if ($attach_id > 0) {
 //and if you want to set that image as Post then use:
 update_post_meta($new_review_id, '_thumbnail_id', $attach_id);
}
}

 return true;
}

 return false;
}
}

 return true;
}
June 7th 19 at 14:35
0 answer

Find more questions by tags WordPress