Answer the question
In order to leave comments, you need to log in
How to save image to library from CF7?
Hello. I'm trying to create a post through CF7 from the front and attach a featured image.
But media_handle_upload always returns a Specified file failed upload test error.
A similar code is not processed through CF7, but simply through a self-written form, and the picture is uploaded to the library. But I really don’t want to write validation myself, send a letter and send a form ajax.
Here is the code:
add_action('wpcf7_before_send_mail', 'create_review_post');
function create_review_post($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;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question