Пожалуйста, проверьте код ниже, чтобы загрузить изображение формы через Ajax
JS CODE
var form = new FormData();
var image = jQuery('#img_avatar')[0].files[0]; //We have only one file and this is how we get it.
//Now we add all the data to the form instance in a key value pair.
//Notice that we called it image here. if you change it then change it in the
//media_handle_upload('image', 0); function as well.
form.append('image', image);
form.append('current_user_id', current_user_id);
form.append('action', 'cvf_upload_files');
//Using localize script to pass "site_url" and "nonce"
jQuery.ajax({
url: ajax_url,
type: 'POST',
data: form,
contentType: false,
processData: false
}).done(function(data){
// console.log("data is: ", data);
}).fail(function(data){
// console.log("errors are: ", error);
});
Вам необходимо добавить тип файла с идентификатором img_avatar
Код WordPress (PHP)
add_action('wp_ajax_cvf_upload_files', 'cvf_upload_files');
add_action('wp_ajax_nopriv_cvf_upload_files', 'cvf_upload_files'); // Allow front-end submission
function cvf_upload_files(){
$parent_post_id = isset( $_POST['post_id'] ) ? $_POST['post_id'] : 0; // The parent ID of our attachments
$valid_formats = array("jpg", "png", "gif", "bmp", "jpeg"); // Supported file types
$max_file_size = 1024 * 500; // in kb
$max_image_upload = 10; // Define how many images can be uploaded to the current post
$wp_upload_dir = wp_upload_dir();
$path = $wp_upload_dir['path'] . '/';
$count = 0;
$photoattach_id = '';
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $parent_post_id,
'exclude' => get_post_thumbnail_id() // Exclude post thumbnail to the attachment count
) );
// Image upload handler
if( $_SERVER['REQUEST_METHOD'] == "POST" ){
// Check if user is trying to upload more than the allowed number of images for the current post
$upload_img = $_FILES['image'];
if($upload_img['size']!=0){
$photoattach_id = '';
$uploadedfile = $upload_img;
$upload_overrides = array( 'test_form' => FALSE );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
} else {
//echo "Possible file upload attack!\n";
}
if ( $movefile) {
$wp_filetype = $movefile['type'];
$filename = $movefile['file'];
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
if($uploadedfile['error']== 0){
$photoattach_id = wp_insert_attachment( $attachment, $filename);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $photoattach_id, $filename );
$res1= wp_update_attachment_metadata( $photoattach_id, $attach_data );
}
}
}
if(!empty($photoattach_id)){
$current_user_id = $_POST['current_user_id'];
if(get_user_meta($current_user_id, 'user_avatar', FALSE)) {
update_user_meta($current_user_id, 'user_avatar', $photoattach_id);
} else { // If the custom field doesn't have a value
add_user_meta($current_user_id, 'user_avatar', $photoattach_id);
}
}
}
exit();
}