Hello, welcome to therichpost.com. In this post, I will tell you how to Upload file in wordpress media library with jquery ajax from frontend form? WordPress is the best cms like I always say. We will also use jquery ajax in it. In my many posts, I always talk about jquery. Jquery helps me lot in my code. I can easily say that jQuery is problem solving.
For file uploading with ajax, we will use formData method.
We will use wp_ajax hook in wordpress for file upload in wordpress media.
Again In this post we will do file uploading in wordpress media library with jquery ajax from frontend form:
Here is the html form code:
<form method=”post”>
<input type=”file” id=”user-file”>
<input type=”submit” name=”Submit” class=”default-btn”>
</form>
Here is the jquery code:
<script type=”text/javascript”>
$(document).ready(function(){
$(“.default-btn”).click(function(event){
event.preventDefault();
var ajaxurl = “<?php echo admin_url(‘admin-ajax.php’); ?>”;
var formData = new FormData();
formData.append(‘updoc’, $(‘input[type=file]’)[0].files[0]);
formData.append(‘action’, “questiondatahtml”);
$.ajax({
url: ajaxurl,
type: “POST”,
data:formData,cache: false,
processData: false, // Don’t process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success:function(data) {
alert(data);},
});
});
});
</script>
And Now Final, here is the wordpress code to Upload file in wordpress media library with jquery ajax from frontend form and you need to add this hook into your wordpress theme’s functions.php file:
add_action( ‘wp_ajax_questiondatahtml’, ‘questiondatahtml_update’ );
add_action( ‘wp_ajax_nopriv_questiondatahtml’, ‘questiondatahtml_update’ );
function questiondatahtml_update() {
if ( $_FILES ) {
require_once(ABSPATH . “wp-admin” . ‘/includes/image.php’);
require_once(ABSPATH . “wp-admin” . ‘/includes/file.php’);
require_once(ABSPATH . “wp-admin” . ‘/includes/media.php’);
$file_handler = ‘updoc’;
$attach_id = media_handle_upload($file_handler,$pid );
}echo “You are done!!”;
wp_die();
}
There are so many hooks in wordpress and i will let you know all. Please do comment if you any query related to this post. Thank you. Therichpost.com
Leave a Reply