I have a professional registration form, where the same is registered by entering name and image (photo). This registration without the use of Ajax, I can do, but it must be done in Ajax, and the image I can not send, even using formData. Here's how my code is right now.
page-register.php
<form id="form-professionals">
<input type="text" id="name" name="name" required placeholder="Insert the Name" value=""/>
<input type="file" name="image" id="image">
<button id="button-register-professionals">Register</button>
<div class="notification-profesionals"></div>
scripts.js
$(document).ready(function () {
$('#button-register-professionals').click(function () {
var name = $('#name').val();
var image = $('#image').val();
if (name == '') {
alert('Required Field');
} else {
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'register_professionals',
name: name,
image: image
},
success: function (response) {
$('.notification-profesionals').html(response);
},
error: function (response) {
console.log('error: ' + response);
}
});
}
return false;
});});
functions.php
add_action('wp_ajax_nopriv_register_professionals', 'register_professionals');
add_action('wp_ajax_register_professionals', 'register_professionals');
function register_professionals(){
$post_type = 'professionals';
$title = $_POST['name'];
$image = $_FILES['image'];
$new_post = array(
'post_title' => $title,
'post_status' => 'pending',
'post_type' => $post_type,
);
wp_insert_post($new_post);
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');
}
if ($image) {
foreach ($image as $file => $array) {
if ($image[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $image[$file]['error'];
}
$attach_id = media_handle_upload($file, $id);
}
} else {
echo 'error - image';
}
if ($attach_id > 0) {
update_post_meta($id, '_thumbnail_id', $attach_id);
echo 'success - add image';
} else {
echo 'error - add image';
}
if ($id) {
echo 'Success';
} else {
echo 'Error';
}
die();
}