Я пытаюсь сделать пользовательскую отправку расширенных пользовательских полей для данных , которые включают в себя поле изображения с использованием ajax без использования собственной отправки, предоставляемой acf.
Может показаться, что изобретать велосипед заново, но этоэто единственный способ, который работает для моего варианта использования, который представляет собой многоступенчатую форму .Из коробки acf не предоставляет для этого функциональности.
В настоящее время я получаю ошибку POST https://dev.energypages.com/wp-admin/admin-ajax.php 400 () , и я не уверен, почему, я был бы очень признателенесли бы новые взгляды могли взглянуть на мой код и посмотреть, могут ли они найти какие-либо проблемы, которые я не могу.
Также мне не удалось получить данные изображения вместе со строковыми данными.
Javascript:
$(".nexttwo").on('click', function() {
resetErrors();
current_fs = $(this).parent();
next_fs = $(this).parent().next();
var comid = getUrlParameter('cid');
var companydata = new FormData(this);
companydata.append("comdata", "company_info");
companydata.append("cid", comid);
$.ajax({
url: ajaxurl,
processData: false,
contentType: false,
dataType: 'json',
method: 'post',
data: companydata,
success: function(data) {
console.log(JSON.stringify(data));
for (var i = 0; i < data.length; i++) {
var status = data[i].code;
var field = data[i].field;
var message = data[i].msg;
//var comid = data[i].cid;
if (status == "200") {
//successful validation
if (animating) return false;
animating = true;
//activate next step on progressbar using the index of next_fs
$("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");
//show the next fieldset
next_fs.show();
//hide the current fieldset with style
current_fs.animate({
opacity: 0
}, {
step: function(now, mx) {
//as the opacity of current_fs reduces to 0 - stored in "now"
//1. scale current_fs down to 80%
scale = 1 - (1 - now) * 0.2;
//2. bring next_fs from the right(50%)
left = (now * 50) + "%";
//3. increase opacity of next_fs to 1 as it moves in
opacity = 1 - now;
current_fs.css({
'transform': 'scale(' + scale + ')'
});
next_fs.css({
'left': left,
'opacity': opacity
});
},
duration: 800,
complete: function() {
current_fs.hide();
animating = false;
},
//this comes from the custom easing plugin
easing: 'easeInOutBack'
});
} else {
var msg = '<label class="acf-notice -error acf-error-message error" for="' + field + '">' + message + '</label>';
$('input[name="' + field + '"], select[name="' + field + '"]').addClass('acf-error').before(msg);
}
}
}
});
});
PHP:
function company_info($post_id){
if( isset($_POST['cid']) )
$post_id = $_POST['cid'];
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-load.php');
//Log form data
$file_path = plugin_dir_path( __FILE__ );
$filename = $file_path.'companyinfo.txt';
//Get form data
$data = $_POST['comdata'];
file_put_contents($filename, $data);
$formdata = array();
parse_str($data, $formdata);
//Prepare company info
$cname = strtolower($formdata['acf']['field_5bef0f8c743f6']);
$clogo = $formdata['acf']['field_5bef0fac743f7'];
$cwebsite = $formdata['acf']['field_5bef100b743f8'];
$cphone = $formdata['acf']['field_5bef1032743f9'];
$caddress = $formdata['acf']['field_5bef108a743fa'];
$errorMSG = [];
/* COMPANY NAME */
if ( empty($cname) ) {
$errorMSG[] = array('code' => 404, 'field' => 'acf[field_5bef0f8c743f6]', 'msg' => 'Company name is required');
}
/* COMPANY LOGO */
if ( empty($clogo) ) {
$errorMSG[] = array('code' => 404, 'field' => 'acf[field_5bef0fac743f7]', 'msg' => 'Company logo is required');
}
$success = [];
if( empty($errorMSG) ){
$uploadedfile = $_FILES['acf[field_5bef0fac743f7]'];
$upload_name = $_FILES['acf[field_5bef0fac743f7]']['name'];
$uploads = wp_upload_dir();
$filepath = $uploads['path']."/$upload_name";
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && !isset( $movefile['error'] ) ) {
$file = $movefile['file'];
$url = $movefile['url'];
$type = $movefile['type'];
$attachment = array(
'post_mime_type' => $type ,
'post_title' => $upload_name,
'post_content' => 'File '.$upload_name,
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file, 0);
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
// Let WordPress handle the upload.
//$img_id = media_handle_upload( 'acf[field_5bef0fac743f7]', 0 );
file_put_contents($filename, $attach_id);
update_field('field_5bef0fac743f7', $attach_id, $post_id);
update_field('field_5bef0f8c743f6', $cname, $post_id);
update_field('field_5bef100b743f8', $cwebsite, $post_id);
update_field('field_5bef1032743f9', $cphone, $post_id);
update_field('field_5bef108a743fa', $caddress, $post_id);
$success[] = array('code' => 200);
echo json_encode($success);
exit();
}
echo json_encode($errorMSG);
exit();
}
add_action('wp_ajax_company_info', 'company_info');
add_action('wp_ajax_nopriv_company_info', 'company_info');
add_action('acf/save_post' , 'company_info', 20 );
HTML ОБЛАСТЬ ИЗОБРАЖЕНИЯ:
<div class="acf-field acf-field-image acf-field-5bef0fac743f7" style="width:50%;" data-name="company_logo" data-type="image" data-key="field_5bef0fac743f7" data-required="1" data-width="50">
<div class="acf-label">
<label for="acf-field_5bef0fac743f7">COMPANY LOGO <span class="acf-required">*</span></label>
</div>
<div class="acf-input">
<div class="acf-image-uploader" data-preview_size="thumbnail" data-library="all" data-mime_types="" data-uploader="basic">
<input name="acf[field_5bef0fac743f7]" value="url=C%3A%5Cfakepath%5C4change-energy-logo.png" type="hidden">
<div class="show-if-value image-wrap" style="max-width: 150px">
<img data-name="image" src="" alt="" class="pk-pin-it-ready">
<div class="acf-actions -hover">
<a class="acf-icon -cancel dark" data-name="remove" href="#" title="Remove"></a>
</div>
</div>
<div class="hide-if-value">
<label class="acf-basic-uploader">
<input name="acf[field_5bef0fac743f7]" id="acf-field_5bef0fac743f7" type="file"> </label>
</div>
</div>
</div>
</div>