Data, Maps, Usability, and Performance

WordPress Upload Files with Ajax

Last updated on January 29, 2015 in Development

WP upload file with ajax

How do you upload files to WordPress with Ajax? Maybe you want fileupload functionality on the front end or enable file uploads in your WordPress plugin. There are a lot of good tutorials on this subject but I couldn’t find any simple example that works with native WP files.

This tutorial on multiple file uploads on the front-end does work but it requires using a server side file for the back end and custom functions in functions.php that use media_handle_upload without Ajax. Tutorials on WordPress file uploads with ajax leverage special jQuery plugins, queuing wordpress scripts, and server side functions to process the Ajax request. This might be needed if you need a lot of control but if you just need to easily upload and delete files, I will show you how to do it in a few lines of simple vanilla JavaScript.

If you check out how WordPress manages media, you will see that a file upload is just a POST call to /wp-admin/async-upload.php. It is an Ajax call that passes form data to that file and formdata consists of 4 attributes:

If you have a regular file input field on the page, you can easily query for the uploaded file and filename from the DOM element. You can retrieve the proper nounce token with php when the page loads via wp_create_nonce(‘media-form’) where media-form is the action for the nounce. This token code happens to be already available in a script tag that gets injected into the bottom of the page with wp_plupload_default_settings. If you see it on your page, you can grab it via _wpPluploadSettings.defaults.multipart_params._wpnonce. Finally, the action is upload-attachment.

So, instead of using jQuery Ajax, we can write a very simple JavaScript XHR request with Form Data to upload any file to WordPress:

This works for me in a plugin admin page and the response is a JSON object with success flag, file url, all kinds of meta data about the file, and nonces for next actions like deleting the file from the media library.


Introduction to WordPress Nonces
Upload Files in WordPress

Tags: , , , ,

Facebook Twitter Hacker News Reddit More...