Last active
June 12, 2021 15:02
-
-
Save guilhermealveslopes/5e96f1e686aa3078d69c6b4f6349da09 to your computer and use it in GitHub Desktop.
Upload file via ajax WORDPRESS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/////////////////////////////////////////////// | |
// PHP | |
/////////////////////////////////////////////// | |
// Create a function to handle files sent through ajax | |
function image_wp_handle_upload($file_handler) { | |
require_once( ABSPATH . 'wp-admin/includes/admin.php' ); | |
require_once(ABSPATH . "wp-admin" . '/includes/image.php'); | |
require_once(ABSPATH . "wp-admin" . '/includes/file.php'); | |
require_once(ABSPATH . "wp-admin" . '/includes/media.php'); | |
$upload = wp_handle_upload( $file_handler, array('test_form' => false ) ); | |
$attachment = array( | |
'post_mime_type' => $upload['type'], | |
'post_title' => sanitize_file_name(basename($upload['url'])), | |
'post_content' => '', | |
'post_status' => 'inherit' | |
); | |
$attach_id = wp_insert_attachment( $attachment, $upload['file'] ); | |
return $attach_id; | |
} | |
// ADD TO A REPEATER FIELD OR A WP AJAX FUNCTION | |
$uploadedfile = $_FILES; | |
foreach($uploadedfile as $galeria){ | |
$imageGallery = image_wp_handle_upload( $galeria ); | |
$row = array( | |
'field_60011e134aa6a' => $imageGallery | |
); | |
add_row('field_60011dfa4aa69', $row, 'user_'. $user_id); | |
} | |
/////////////////////////////////////////////// | |
// JAVASCRIPT | |
/////////////////////////////////////////////// | |
$('#user_register').on('submit', function(e){ | |
var fd = new FormData(document.querySelector('#user_register')); // Select form DOM element | |
var names = []; | |
var file_data = $('#files')[0].files; // FILES is ID from input file | |
for(var i = 0;i<file_data.length;i++){ | |
fd.append("file_"+i, file_data[i]); | |
} | |
fd.append('file[]',names); | |
fd.append('action','register'); // Name of AJAX function | |
var serializeDados = $(this).serialize(); | |
$.ajax({ | |
url: ajaxUrl, | |
data:fd, | |
contentType: false, | |
processData: false, | |
type:'POST', | |
success:function(data){ | |
console.log(data); | |
}, | |
beforeSend : function(d){ | |
} | |
}); | |
return false; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment