How to upload file using ajax in WordPress

How to upload file using ajax in WordPress

Hello, welcome to PHPKIDA, If your question like “how to upload file in WordPress using ajax?” then this article for you. We will show you step by step how to Upload file in WordPress media library using frontend form with the help of jquery ajax without using any plugin?

WordPress is the world’s most popular and wide use of cms. We can build any kind of website in WordPress and while we developing any website in WordPress some time we have to give file uploading functionality to user from front end without using plugins due to security or unless loading issue.

Note:

  1. Use (enctype=”multipart/form-data”) form attribute for upload file
  2. For file uploading with ajax, we are using formData method.
  3. We are using wp_ajax hook in WordPress for file upload in WordPress media.
  4. Here we are also rename of uploading file and removing all special character.
  5. File will be upload into like: “yourdomain.com/wp-content/uploads/2020/04/filename”

Create HTML Form

<form id="formId" method="post" enctype="multipart/form-data" autocomplete="off">
	<p>Upload File</p>
	<input type="file" name="file" id="file" />
	/* Create Security nonce */
	<input name="security" value="<?php echo wp_create_nonce("uploadingFile"); ?/>" type="hidden">
	
	// set action name
	<input name="action" value="upload_file" type="hidden"/>
	<input name="submit" value="upload" type="submit"/>
</form>

Submit ajax Request jQuery code

Get and send data request to server when submit button clicked. For file uploading with ajax, we are using formData method.

You can also validate image before uploading using on change read this article: How to validate image file on chnage

jQuery(document).ready(function(e){
	// Submit form data via Ajax
    jQuery("#formId").on('submit', function(e)
	{
        e.preventDefault();
		
		// get file field value using field id
		var fileInputElement = document.getElementById("file");
  		var fileName = fileInputElement.files[0].name;
		
		
		if(trim(fileName)=="")
		{
			alert('Upload your file');
			return false;
		}
		else
		{
			var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
			jQuery.ajax({
				url:ajax_url,
				type:"POST",
				processData: false,
				contentType: false,
				data:  new FormData(this),
				success : function( response ){
					var returnedData = JSON.parse(response);
					if(returnedData.code == 200){
						alert('File uploaded!');
					}else{
						alert(returnedData.msg);
					}
				},
			});
			return false;
		}
		return false;
    });
});

WordPress/PHP code

And Now Final, here is the WordPress code to Upload file in WordPress media library with the help of jquery ajax from frontend form and you need to add (copy/past) below code into your WordPress theme’s functions.php file:

  • We are using wp_ajax hook in WordPress for file upload in WordPress media.
  • Here we are also rename of uploading file and removing all special character.
  • File uploading folder sample path: “yourdomain.com/wp-content/uploads/2020/04/filename”
// create hook for file uploading
add_action('wp_ajax_nopriv_upload_file', 'upload_file_callback');
add_action( 'wp_ajax_upload_file', 'upload_file_callback' );

function upload_file_callback(){
	// check security nonce which one we created in html form and sending with data.
	check_ajax_referer('uploadingFile', 'security');

	// removing white space
	$fileName = preg_replace('/\s+/', '-', $_FILES["file"]["name"]);

	// removing special character but keep . character because . seprate to extantion of file
	$fileName = preg_replace('/[^A-Za-z0-9.\-]/', '', $fileName);

	// rename file using time
	$fileName = time().'-'.$fileName;

	// upload file
	if(wp_upload_bits($fileName, null, file_get_contents($_FILES["file"]["tmp_name"])))
	{
		echo json_encode(['code'=>200]);
	}
	else{
		echo json_encode(['code'=>404, 'msg'=>'Some thing is wrong! Try again.']);
	}
}

Relative Keywords:
how to upload file in wordpress by ajax, how to integrate ajax file upload in wordpress, image upload using ajax in wordpress frontend, wordpress file upload code, ajax file upload with progress bar wordpress, wordpress frontend file upload, upload file using ajax, multiple file upload in wordpress using ajax, formdata ajax wordpress

About Author

My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.