You can upload files via AJAX in WordPress when they’re added to a multiple file input by using the jQuery Form Plugin and the WordPress AJAX API. Here’s a high-level overview of the steps you would need to follow:
- Enqueue the jQuery Form Plugin in your WordPress theme:
phpCopy codefunction my_scripts() {
wp_enqueue_script( 'jquery-form', 'https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js', array( 'jquery' ), '4.3.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
- Add a multiple file input to your form:
pythonCopy code<form id="my-form">
<input type="file" name="my_files[]" multiple>
<input type="submit" value="Upload">
</form>
- Use the jQuery Form Plugin to submit the form and upload the files via AJAX:
javascriptCopy codejQuery( document ).ready( function( $ ) {
$( '#my-form' ).submit( function( e ) {
e.preventDefault();
$( this ).ajaxSubmit({
url: ajaxurl,
type: 'post',
data: {
action: 'my_file_upload',
security: my_ajax_nonce
},
success: function( response ) {
console.log( response );
}
});
});
});
- Process the file upload in the WordPress AJAX action:
phpCopy codefunction my_file_upload() {
check_ajax_referer( 'my_ajax_nonce', 'security' );
if ( isset( $_FILES['my_files'] ) ) {
foreach ( $_FILES['my_files']['tmp_name'] as $key => $tmp_name ) {
$file = array(
'name' => $_FILES['my_files']['name'][$key],
'type' => $_FILES['my_files']['type'][$key],
'tmp_name' => $_FILES['my_files']['tmp_name'][$key],
'error' => $_FILES['my_files']['error'][$key],
'size' => $_FILES['my_files']['size'][$key]
);
$upload = wp_handle_upload( $file, array( 'test_form' => false ) );
if ( ! isset( $upload['error'] ) && isset( $upload['file'] ) ) {
$file_path = $upload['file'];
// do something with the file
}
}
}
wp_die();
}
add_action( 'wp_ajax_my_file_upload', 'my_file_upload' );
Note: This is just a basic example to give you an idea of how to upload files via AJAX in WordPress when added to a multiple file input. You’ll need to modify the code to fit your specific
(Visited 2 times, 1 visits today)
Was this article helpful?
YesNo
Last modified: March 3, 2023