Wordpress - Upload multiple files using wp_handle_upload
We are going to use Ajax and PHP to perform multiple file uploads in a wordpress plugin.
jQuery Ajax code. To send files.
Wordpress PHP to handle uploads.
-----------------------------------------------------------
RESULT
jQuery Ajax code. To send files.
$("#button_id").click(function(e){ e.preventDefault(); var filedata = document.getElementById("inputGroupFiles"), formdata = false; if (window.FormData) { formdata = new FormData(); } var len = filedata.files.length, img, reader, file; for (var i = 0; i < len; i++) { file = filedata.files[i]; if (formdata) { formdata.append("file[]", file); } } formdata.append('action', 'my_action_upload_logos'); jQuery.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', type: 'post', contentType: false, processData: false, data: formdata, success: function (response) { alert(response); // jQuery('.Success-div').html("Form Submit Successfully") } }); });
Wordpress PHP to handle uploads.
<?php add_action( 'wp_ajax_my_action_upload_logos', 'my_action_upload_logos' ); function my_action_upload_logos() { //global $wpdb; // this is how you get access to the database if (!function_exists('wp_handle_upload')) { require_once(ABSPATH . 'wp-admin/includes/file.php'); } // echo $_FILES["upload"]["name"]; $upload_overrides = array('test_form' => false); $files = $_FILES['file']; foreach ($files['name'] as $key => $value) { if ($files['name'][$key]) { $file = array( 'name' => $files['name'][$key], 'type' => $files['type'][$key], 'tmp_name' => $files['tmp_name'][$key], 'error' => $files['error'][$key], 'size' => $files['size'][$key] ); $movefile = wp_handle_upload($file, $upload_overrides); if ($movefile && !isset($movefile['error'])) { echo "Uploaded Successfully"; } else { echo $movefile['error']. '</br>'; } } } wp_die(); // this is required to terminate immediately and return a proper response } ?>
-----------------------------------------------------------
RESULT
Comments
Post a Comment