Мы создали форму с помощью cf7 и создали поле изображения с помощью плагина «Оптимизация и загрузка изображений CF7», и теперь мы хотим сохранить все введенные данные в cpt, но не можем сохранить изображение cf7 в поле изображения acf этого конкретного cpt, вот мой код :
function save_posted_data( $posted_data ) {
$args = array(
'post_type' => 'prescriptions',
'post_status'=>'draft',
'post_title'=>$posted_data['phonenumber'],
);
$post_id = wp_insert_post($args);
if (!is_wp_error($post_id)){
if ( isset($posted_data['location']) ){
update_post_meta($post_id, 'location', $posted_data['location']);
}
if ( isset($posted_data['phonenumber']) ){
update_post_meta($post_id, 'contact_number', $posted_data['phonenumber']);
}
if ( isset($posted_data['prescriptiontext']) ){
update_post_meta($post_id, 'prescription_description', $posted_data['prescriptiontext']);
}
if ( !function_exists('wp_handle_upload') ) {
require_once(ABSPATH . 'wp-admin/includes/file.php');
}
// Move file to media library
$movefile = wp_handle_upload( $_FILES[$posted_data['prescriptionimage']], array('test_form' => false) );
// If move was successful, insert WordPress attachment
if ( $movefile && !isset($movefile['error']) ) {
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($movefile['file']),
'post_mime_type' => $movefile['type'],
'post_title' => preg_replace( '/\.[^.]+$/', "", basename($movefile['file']) ),
'post_content' => "",
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $movefile['file']);
update_field('prescription_image', $attach_id, $post_id);
}
//and so on ...
return $posted_data;
}
}
add_filter( 'wpcf7_posted_data', 'save_posted_data' );
Это мой код, а $posted_data['prescriptionimage'] — это имя поля изображения в cf7, а изображение сохранено как 1191566397/ID_file_download.png, как это. Мы не знали, что не так в коде, может ли кто-нибудь мне помочь
У меня есть фрагмент кода, который может вам помочь. Без того, чтобы я конкретно отвечал на ваш вопрос, я считаю, что это укажет вам правильное направление. Вы должны не цеплять wpcf7_posted_data
, а цеплять wpcf7_before_send_mail
, где вы можете получить опубликованные данные. В моем случае я добавил вложение и включил метаданные автора. Но я считаю, что с этим вы можете понять, как добавить в свое поле ACF? Я заставил $posted_data
вернуть то, что у вас есть выше.
<?php
add_action( 'wpcf7_before_send_mail', 'he_cf7_process_form', 10, 1);
/**
* @param object $contact_form The UserID of the Poster
*/
function he_cf7_process_form($contact_form) {
// check to make sure it only fires on your contact form
if ( $contact_form->id() == integer_of_your_contact_form ) return;
// Get the contact form submitted data
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$posted_data = $submission->get_posted_data();
$uploaded_files = $submission->uploaded_files();
} else {
return;
}
// Your field name of the file goes here
$files = $_FILES['field-name'];
if (empty($uploaded_files)) {
return 0;
} else {
$image_name = basename($uploaded_files['field-name']);
$image_location = $uploaded_files['field-name'];
$image_content = file_get_contents($image_location);
$wp_upload_dir = wp_upload_dir();
$upload = wp_upload_bits($image_name, null, $image_content);
$filename = $upload['file'];
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
'post_mime_type' => $files['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $filename);
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata($attach_id, $filename);
wp_update_attachment_metadata($attach_id, $attach_data);
$arg = array(
'ID' => $attach_id,
'post_author' => $userid,
);
wp_update_post($arg);
}
}