How to Integrate Ajax File Upload in WordPress

Do you want to implement Ajax file upload in WordPress? Sometimes, you need to perform a task which uploads a file through Ajax. In this article, we study how to do Ajax file upload in WordPress.

A benefit of doing file uploading through Ajax is it reduces your server load. Your page will not reload which saves extra calls to a server and so the bandwidth. It also adds a better user experience on your website.

Normally while working with Ajax, we give a call to URL and pass data to or get data from the specified URL. WordPress has a slightly different way to perform Ajax operations. In WordPress, we do give a call to the URL but the code we write to process the data will go in the function. Then this function needs to map with the ‘action’ value passed in Ajax parameters. Confused? Let’s see it in action.

Ajax File Upload in WordPress

For getting started, you need a form with the file input. We give an Ajax call on the selection of a file and upload the file to a server. To create a form, add the below HTML to your page template.

<form class="fileUpload" enctype="multipart/form-data">
    <div class="form-group">
        <label><?php _e('Choose File:'); ?></label>
        <input type="file" id="file" accept="image/*" />
    </div>
</form>

Next, you have to give an Ajax call on the change event of file input. As we are passing a file content to the Ajax, your code will be slightly different compared to regular jQuery code of WordPress Ajax.

Include JS File in WordPress

Let’s first include the JS file in a WordPress environment. This code will go inside functions.php file or in a site-specific plugin.

function aw_scripts() {
    // Register the script
    wp_register_script( 'aw-custom', get_stylesheet_directory_uri(). '/js/custom.js', array('jquery'), '1.1', true );

    // Localize the script with new data
    $script_data_array = array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
    );
    wp_localize_script( 'aw-custom', 'aw', $script_data_array );

    // Enqueued script with localized data.
    wp_enqueue_script( 'aw-custom' );
}

add_action( 'wp_enqueue_scripts', 'aw_scripts' );

Upload File on Server

You are ready with the form and JS file. Now, add the code below in the JS file which will send file content to the server-side through Ajax.

custom.js

jQuery(function($) {
    $('body').on('change', '#file', function() {
        $this = $(this);
        file_data = $(this).prop('files')[0];
        form_data = new FormData();
        form_data.append('file', file_data);
        form_data.append('action', 'file_upload');

        $.ajax({
            url: aw.ajaxurl,
            type: 'POST',
            contentType: false,
            processData: false,
            data: form_data,
            success: function (response) {
                $this.val('');
                alert('File uploaded successfully.');
            }
        });
    });    
});

The important part of the above code is, we append an action ‘file_upload’ to the form_data object. We will use this ‘file_upload’ action to proceed with the form data.

In the functions.php, map this action with the Ajax as follows:

add_action( 'wp_ajax_file_upload', 'file_upload_callback' );
add_action( 'wp_ajax_nopriv_file_upload', 'file_upload_callback' );

If you are writing this code in a plugin then you don’t need to write a second statement. Here to the ‘wp_ajax_’ and ‘wp_ajax_nopriv_’ we append the action value which is ‘file_upload’. The second parameter ‘file_upload_callback’ is the callback method which will have actual code for file uploading.

function file_upload_callback() {
       $arr_img_ext = array('image/png', 'image/jpeg', 'image/jpg', 'image/gif');
    if (in_array($_FILES['file']['type'], $arr_img_ext)) {
        $upload = wp_upload_bits($_FILES["file"]["name"], null, file_get_contents($_FILES["file"]["tmp_name"]));
        //$upload['url'] will gives you uploaded file path
    }
    wp_die();
}

I am using a wp_upload_bits method for uploading file on a server. This method directly stores a file inside wp-content/uploads directory.

Go ahead and try to upload a file. Your file should be uploaded to the wp-content/uploads/ folder. Keep note you will find your file into the current month folder of uploads directory.

Upload Multiple Files Using Ajax in WordPress

So far we have discussed uploading a single file through Ajax. There might be a situation when you want to upload multiple files using Ajax. Let’s see how to achieve it.

For uploading multiple files, you need to do slight changes in the above HTML, JS, and PHP code.

HTML provides a ‘multiple’ attribute which allows a user to select multiple files on file input.

HTML Code

<form class="fileUpload" enctype="multipart/form-data">
    <div class="form-group">
        <label><?php _e('Choose File:'); ?></label>
        <input type="file" id="file" accept="image/*" multiple />
    </div>
</form>

As a user going to select multiple files we need to change the JavaScript code which loops through each file and builds an array out of it.

custom.js

jQuery(function($) {
    $('body').on('change', '#file', function() {
        $this = $(this);
        file_obj = $this.prop('files');
        form_data = new FormData();
        for(i=0; i<file_obj.length; i++) {
            form_data.append('file[]', file_obj[i]);
        }
        form_data.append('action', 'file_upload');

        $.ajax({
            url: aw.ajaxurl,
            type: 'POST',
            contentType: false,
            processData: false,
            data: form_data,
            success: function (response) {
                $this.val('');
                alert('File(s) uploaded successfully.');
            }
        });
    });
});

And finally, in the Ajax callback function, we loop through the file array and upload each file on a server.

function file_upload_callback() {
    $arr_img_ext = array('image/png', 'image/jpeg', 'image/jpg', 'image/gif');

    for($i = 0; $i < count($_FILES['file']['name']); $i++) {

        if (in_array($_FILES['file']['type'][$i], $arr_img_ext)) {

            $upload = wp_upload_bits($_FILES['file']['name'][$i], null, file_get_contents($_FILES['file']['tmp_name'][$i]));
            //$upload['url'] will gives you uploaded file path
        }
    }
    wp_die();
}

I hope you got to know about the Ajax file upload in WordPress. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

13 thoughts on “How to Integrate Ajax File Upload in WordPress

  1. AJAX calls in WP are not working with contentType: false or processData: false. I never managed to get it working like this.

  2. how to upload multiple file

    i’m use

    		  	var number = document.getElementById('file');
    		  	for (var i = 0; i < number; i++) {
               		//var 'file_data_'+i = $(this).prop('files')[i];	
    				//window['file_data_' + i ] = $(this).prop('files')[i];
                	var file_data = $('#file').prop('files')[0];	
    
    		  	}
    

    but not working

  3. Finally, someone that understands the special nuances of WP and AJAX! I was so close before this article, but couldn’t figure out how to pass my ‘action’… Didn’t think to put it inside the FormData… This line was the winner: form_data.append(‘action’, ‘file_upload’); THANK YOU

    1. Another way to do this is via HTML: input name=”action” type=”hidden” value=”action_name”
      which will include the action in the form data

Leave a Reply

Your email address will not be published. Required fields are marked *